【问题标题】:XAML bind to DependencyProperty instance held in a CLR propertyXAML 绑定到 CLR 属性中保存的 DependencyProperty 实例
【发布时间】:2013-08-15 04:26:12
【问题描述】:

如何从 XAML 绑定到 CLR 属性中保存的 DependencyProperty 实例?

我正在尝试生成一个“设置”列表(用户可以通过复选框列表修改应用程序设置)。

我希望从某个类 (MyOptions) 中的依赖属性动态创建列表。我已经实现了,我将 ListBox 绑定到这个列表(这是一个 DependencyProperty objs 的列表)

public IEnumerable<OptionProperty> AvailableOptions
{
    get
    {
         return from  property in GetAttachedProperties(MyOptions) 
                where property.GetMetadata(MyOptions) is OptionPropertyMetaData
                select new OptionProperty { OptionName = property.Name, OptionType = property.PropertyType, OptionDependencyProperty = property };
    }
}

我需要做的是将 DataTemplate(用于 ListBox)中的复选框绑定到列表中的 DependencyProperty 项。

所以这当然行不通

<DataTemplate DataType="{x:Type local:OptionProperty}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="30"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Text="{Binding Path=OptionName}" />
        <CheckBox Grid.Column="1" HorizontalAlignment="Right" IsChecked="{Binding Path=OptionDependencyProperty}"></CheckBox>
    </Grid>   
</DataTemplate>

因为它只是绑定到名为 OptionDependencyProperty 的 OptionProperty 的属性,而不是 OptionDependencyProperty 中引用的 DependencyProperty。

那么如何从 XAML 绑定到 CLR 属性 (OptionDependencyProperty) 中保存的 DependencyProperty 实例?

我认为我的大脑已经满了,不能再处理抽象了:(

谢谢!

【问题讨论】:

  • 您确定在您的(视图)模型中需要依赖属性吗?你能解释一下,为什么?此外,OptionProperty 声明将很有用。
  • @Dennis,这个决定是不久前做出的,但我相信这主要是为了让我的图书馆用户可以从 xaml 进行设置,这样他们就可以执行 - 好消息是我不必将控件的属性映射到选项类,我只需在 '控件的选项属性。我的印象是使用 DP 并不比 CLR 属性重多少。

标签: c# wpf binding


【解决方案1】:

DependencyProperty 不是值容器。它是一个标识符,可用于获取/设置特定实例的值。

而不是问“这个依赖属性的值是什么?”你想问,“这个实例的这个依赖属性的值是什么?”

OptionProperty 类中绑定到不同的属性可能会更好。

类似的东西:

public class OptionProperty : INotifyPropertyChanged
{
    public MyOptions MyOptions { get; set; }

    public DependencyProperty OptionDependencyProperty { get; set; }

    public object Value
    {
        get
        {
            return MyOptions.GetValue(OptionDependencyProperty);
        }
        set
        {
            MyOptions.SetValue(OptionDependencyProperty, value);
            RaisePropertyChanged("Value");
        }
    }
    // TODO Implement INotifyPropertyChanged
    // TODO All of the other properties
}

然后您可以绑定到 Value 属性,该属性将为您的 MyOptions 实例上的 DependencyProperty 获取并设置适当的值。

【讨论】:

    猜你喜欢
    • 2019-09-07
    • 1970-01-01
    • 2012-01-31
    • 2019-07-11
    • 2011-07-02
    • 1970-01-01
    • 2020-12-29
    • 2012-09-20
    • 1970-01-01
    相关资源
    最近更新 更多