代码之家  ›  专栏  ›  技术社区  ›  Drake

如何在自定义控件中绑定

wpf
  •  2
  • Drake  · 技术社区  · 6 年前

    在我的WPF应用程序中,我创建了自己的控件并希望绑定到其中的属性。这就是我目前所尝试的:

    public partial class BreadcrumbContainer : Grid
    {
        public static readonly DependencyProperty TestProperty =
        DependencyProperty.Register(nameof(Test), typeof(string), typeof(BreadcrumbContainer), new PropertyMetadata(string.Empty));
    
        public string Test
        {
            get { return (string)GetValue(TestProperty); }
            set { SetValue(TestProperty, value); Refresh(); }
        }
    
        public BreadcrumbContainer()
        {
            InitializeComponent();
        }
    
        private void Refresh()
        {
            // never gets called
        }
    }
    

    我试着和我的 Test

    <controls:BreadcrumbContainer Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Test="{Binding SearchMessage}"/>
    

    在我的视图模型中,我有一个属性 SearchMessage . 我所有的其他绑定都在工作,所以这一定是我在工作中做错了什么 BreadcrumbContainer

    1 回复  |  直到 6 年前
        1
  •  3
  •   Clemens    6 年前

    引用亚当·内森的WPF

    XAML中的依赖项属性。尽管XAML编译器依赖于 属性包装器在编译时,WPF调用底层 在运行时直接使用GetValue和SetValue方法!

    您案例中的属性包装器是您的 Test 财产。所以基本上,不要把任何逻辑放在里面,因为它在运行时永远不会被调用。正确的方法是使用属性更改回调。答案就是一个例子 found here . 请注意 DependencyProperty.Register 打电话。

    Checklist for Defining a Dependency Property - 实现“包装器” :

    在除特殊情况外的所有情况下,包装器实现都应该分别执行GetValue和SetValue操作。原因将在本主题中讨论 XAML Loading and Dependency Properties

    XAML加载和依赖属性 :

    这是WPF中一个令人困惑的行为的例子,如果你不知道的话,它会让你发疯。这其实不是你的错,但我建议你阅读亚当·内森发布的WPF——以及所有的在线文档——来更多地了解这些类型的陷阱。