使用Dependency属性设置标签内容

时间:2010-08-18 11:06:26

标签: c# xaml dependency-properties

我很难理解如何在C#和xaml代码之间使用依赖属性。 这是我的问题的一个小代码示例

XAML代码:

<Window x:Class="WpfChangeTextApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <Label Name="statusTextLabel" Content="{Binding StatusText}"></Label>
    <Button Name="changeStatusTextButton" Click="changeStatusTextButton_Click">Change Text</Button>
</StackPanel>

C#代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();            
    }

    public string StatusText
    {
        get { return (string)GetValue(StatusTextProperty); }
        set { SetValue(StatusTextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for StatusText.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty StatusTextProperty =
        DependencyProperty.Register("StatusText", typeof(string), typeof(MainWindow));

    private void changeStatusTextButton_Click(object sender, RoutedEventArgs e)
    {
        StatusText = "Button clicked";
    }
}

所以,我的麻烦是当我点击按钮时,Label statusTextLabel没有更新。我的麻烦是我不知道代码的哪个部分我做错了什么,是在xaml还是在C#中?在xaml中我可能在绑定中做错了什么?或者我错过了在C#代码中做某事?

1 个答案:

答案 0 :(得分:2)

默认情况下,绑定路径相对于当前元素的DataContext属性。您尚未将其设置为任何内容,因此无法解析绑定。如果要在窗口类上使用StatusText属性,则有两种方法。一种是使用与FindAncestor的RelativeSource的绑定来查找树中的Window并直接绑定到它的属性:

<Label Name="statusTextLabel" Content="{Binding StatusText, 
    RelativeSource={RelativeSource AncestorType=Window}}"></Label>

另一种方法是将Window的DataContext设置为自身,因此它将由标签继承。例如,在构造函数中:

public MainWindow()
{
    this.DataContext = this;
    InitializeComponent();
}

对于大多数应用程序,您实际上需要一个单独的类来表示数据,并且您将该类的实例设置为DataContext。您还可以使用普通CLR属性而不是依赖项属性,但如果您希望在属性更改时通知UI,则需要实现INotifyPropertyChanged。在编写自定义控件并希望用户能够使用数据绑定设置属性时,依赖项属性更有用。

相关问题