WPF 用户控件属性绑定 [英] WPF UserControl property binding

查看:151
本文介绍了WPF 用户控件属性绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个包含 2 个按钮的 WPF UserControl.我在一个窗口中使用这个 UserControl 并应用一个 Window.Resource 值来设置用户控件内一个按钮的背景.

I'm trying to create a WPF UserControl which contains 2 buttons. I use this UserControl in a Window and apply a Window.Resource value to set the background of one button inside the user control.

目前我有:

  • window.xaml

  • window.xaml

<Window.Resources>
    <SolidColorBrush Color="Brown" x:Key="theBG"></SolidColorBrush>
</Window.Resources>
<theControl:TheControl  
    x:Name="TheControl" 
    buttonBG="{Binding Source={StaticResource theBG}}" />

  • usercontrol.xaml.cs

  • usercontrol.xaml.cs

    public SolidColorBrush buttonBG
    {
        get { return base.GetValue(buttonBGProperty) as SolidColorBrush; }
        set { base.SetValue(buttonBGProperty, value); }
    }
    public static readonly DependencyProperty buttonBGProperty = DependencyProperty.Register("buttonBG", typeof(SolidColorBrush), typeof(DataPanel), null);
    

  • usercontrol.xaml

  • usercontrol.xaml

    <Button ... Background="{Binding buttonBG}">
    

  • 我原以为这会起作用,但背景不是我在窗口资源中设置的背景.

    I was expecting this to work but the background is not the one I set in the window resource.

    我做错了什么?

    推荐答案

    Background="{Binding buttonBG}"
    

    暗示您更改了 UserControlDataContext,您永远不应该.或者绑定错误.

    Implies either that you changed the DataContext of the UserControl, which you should never do. Or that the binding is just wrong.

    使用

    Background="{Binding buttonBG, ElementName=control}"
    

    命名您的 UserControl 根元素 control.RelativeSource 也能正常工作.

    Naming your UserControl root element control. RelativeSource works as well.

    这篇关于WPF 用户控件属性绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆