绑定动态对象wpf

时间:2011-11-18 15:31:37

标签: c# wpf binding

我正在尝试绑定一个可以动态更改为显示元素的自定义对象。

我的window.xaml现在有这个:

<StackPanel Height="310" HorizontalAlignment="Left" Margin="12,12,0,0" Name="Configuration_stackPanel" VerticalAlignment="Top" Width="264" Grid.Column="1">
<Label Content="{Binding Path=Client}" Height="22" HorizontalAlignment="Left" Margin="20,0,0,0" Name="Client" VerticalAlignment="Top" />
</StackPanel>

在window.xaml.cs中,我有

的成员
public CustomObject B;

CustomObject有一个客户端成员。 B.Client,获取客户端名称(这是一个字符串)等

如何显示B.Client并在代码更改时更改它。

ie:如果在代码中我做B.Client =&#34; foo&#34;然后显示foo 如果我做B.Client =&#34; bar&#34;,则显示bar而不是foo。

提前致谢
˚F

1 个答案:

答案 0 :(得分:2)

您的CustomObject课程必须实施INotifyPropertyChanged界面:

public class CustomObject : INotifyPropertyChanged
{

    private string _client;
    public string Client
    {
        get { return _client; }
        set
        {
            _client = value;
            OnPropertyChanged("Client");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        handler(this, new PropertyChangedEventArgs(propertyName));
    }

}