2011-11-18 113 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