Свойство зависимости в Page - PullRequest
       0

Свойство зависимости в Page

0 голосов
/ 03 сентября 2011

Я хочу определить DependencyProeprty в моем классе Window, как показано в следующем коде.

namespace dgCommon
{

    //MenuPage is a Page.
    public partial class MenuPage : IFrameInterop
    {

        public Style MenuIconStyle { get { return (Style)GetValue(MenuIconStyleProperty); } set { SetValue(MenuIconStyleProperty, value); } }
        public static readonly DependencyProperty MenuIconStyleProperty = DependencyProperty.Register("MenuIconStyle", typeof(Style), typeof(MenuPage), new UIPropertyMetadata(null));
    ...

В пользовательском элементе управления этот код включает свойство зависимости. Но на следующей странице XAML не компилируется.

<Page x:Class="dgCommon.MenuPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:dgCommon="clr-namespace:dgCommon" 

      <!--following line is problem.-->
      MenuIconStyle="{StaticResource MenuButtonStyle}"

      x:Name="pageMenu">
...

В чем причина?

Ответы [ 3 ]

2 голосов
/ 03 сентября 2011

Вы не можете использовать назначить свойство зависимости в XAML элемента управления / окна / страницы, который его объявляет.Если вы хотите установить его значение по умолчанию, сделайте это с выделенным кодом.

1 голос
/ 03 сентября 2011

На этот вопрос ответили здесь: Установка пользовательского свойства на странице WPF / Silverlight
Причина этой проблемы также объясняется в ссылке.

У вас есть несколько вариантов назначения вашего пользовательского свойства зависимости в Xaml

Вариант 1 . Создайте базовый класс для Page, куда вы добавите свой DP

MenuPage.xaml

<dgCommon:MenuPageBase x:Class="dgCommon.MenuPage" 
                       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                       xmlns:dgCommon="clr-namespace:dgCommon"
                       MenuIconStyle="{StaticResource MenuButtonStyle}">
    <!--...-->
</dgCommon:MenuPageBase>

MenuPage.xaml.cs

public partial class MenuPage : MenuPageBase
{
    // ...
}

MenuPageBase.cs

public class MenuPageBase : Page
{
    public static readonly DependencyProperty MenuIconStyleProperty =
        DependencyProperty.Register("MenuIconStyle",
                                    typeof(Style),
                                    typeof(MenuPage),
                                    new UIPropertyMetadata(null));
    public Style MenuIconStyle
    {
        get { return (Style)GetValue(MenuIconStyleProperty); }
        set { SetValue(MenuIconStyleProperty, value); }
    }
}

Опция 2. Реализация статических методов get и set для MenuIconStyle

MenuPage.xaml

<Page x:Class="dgCommon.MenuPage" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:dgCommon="clr-namespace:dgCommon"
      dgCommon.MenuPage.MenuIconStyle="{StaticResource MenuButtonStyle}">

MenuPage.xaml.cs

public partial class MenuPage : Page
{
    public static readonly DependencyProperty MenuIconStyleProperty =
        DependencyProperty.Register("MenuIconStyle",
                                    typeof(Style),
                                    typeof(MenuPage),
                                    new UIPropertyMetadata(null));
    public Style MenuIconStyle
    {
        get { return (Style)GetValue(MenuIconStyleProperty); }
        set { SetValue(MenuIconStyleProperty, value); }
    }
    public static void SetMenuIconStyle(Page element, Style value)
    {
        element.SetValue(MenuIconStyleProperty, value);
    }
    public static Style GetMenuIconStyle(Page element)
    {
        return (Style)element.GetValue(MenuIconStyleProperty);
    }
    // ...
}

Вариант 3. Используйте Attached Properties, как указали другие люди.

0 голосов
/ 03 сентября 2011

Как сказал Томас, чтобы присвоить DP значение по умолчанию в коде позади окна, замените

new UIPropertyMetadata(null) на new UIPropertyMetadata(DEFAULT_VALUE_HERE)

При этом DP - этодовольно бесполезно, если вы не обращаетесь к нему в своем представлении, вы можете получить доступ к этому DP в xaml, сначала присвоив имя своему элементу управления:

<Page x:Class="dgCommon.MenuPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:dgCommon="clr-namespace:dgCommon" 
      x:Name="pageMenu" />

Затем вызвав DP следующим образом:

<Page x:Class="dgCommon.MenuPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:dgCommon="clr-namespace:dgCommon" 
      x:Name="pageMenu" Style="{Binding MenuIconStyle, ElementName=pageMenu}" />

Теперь, если вы действительно хотите иметь свойство в окне, которое называется MenuIconStyle, вам придется изучить вложенные свойства

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...