2011-11-18 145 views
0

我想绑定一个自定义对象,可以动态地将其更改为displaed元素。绑定动态对象wpf

我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 =“foo”,那么foo显示为 ,如果我做的是B.Client =“bar”,bar会显示而不是foo。

在此先感谢
˚F

+0

可以提供CustomObject请的定义是什么? –

回答

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)); 
    } 

} 
+0

我不需要在xaml中添加一些内容来告诉它在哪里寻找客户端? – djfoxmccloud

+0

你只需要绑定到属性。当值更改时,绑定将自动更新。 –

+0

这不起作用,这就是为什么我问。我不应该添加类似StaticResource或xaml的其他内容吗? – djfoxmccloud