【问题标题】:WPF XAML custom attribute on local data template本地数据模板上的 WPF XAML 自定义属性
【发布时间】:2018-02-15 16:58:42
【问题描述】:

WPF 新手。我想将参数传递给视图。我想我可以使用控件的一个属性:

<DataTemplate x:Key="ListTemplate">
    <local:ListView TestValue="foo" />
</DataTemplate>

...最终带有Binding,但我不知道如何添加TestValue,以使其被后面的代码识别。

我该如何解决这个问题,或者有更好的方法吗?

【问题讨论】:

    标签: .net wpf xaml mvvm


    【解决方案1】:

    您应该在 ListView 类中实现依赖属性:

    public class ListView : UserControl
    {
        public ListView()
        {
            InitializeComponent();
        }
    
        public string TestValue
        {
            get { return (string)this.GetValue(TestValueProperty); }
            set { SetValue(TestValueProperty, value); }
        }
    
        public static readonly DependencyProperty TestValueProperty 
            = DependencyProperty.Register(nameof(TestValue), typeof(string), typeof(ListView));
    }
    

    如何:实现依赖属性: https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/how-to-implement-a-dependency-property

    然后您可以将此属性绑定到您的DataContext 的属性,即您的DataTemplate 应用到的对象:

    <DataTemplate x:Key="ListTemplate">
        <local:ListView TestValue="{Binding SomeSourceProperty}" />
    </DataTemplate>
    

    【讨论】:

    • 啊,DependencyProperty 是缺少的成分。干杯,现在试试看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多