2012-02-05 121 views
1

我的解決方案在MVVM中實現。該視圖是託管用戶控件的窗口。我已經創造了這個用戶控件,如下一個依賴屬性:UserControl中的依賴屬性綁定

public static DependencyProperty ListProperty = DependencyProperty.Register(
     "ItemsList", typeof(List<RequiredClass>), typeof(UsercontrolTest)); 

public List<RequiredClass> ItemsList 
{ 
    get { return (List<RequiredClass>)GetValue(ListProperty); } 
    set 
    { 
     SetValue(ListProperty, value); 
    } 
} 

此屬性在XAML綁定到我的視圖模型屬性(LISTOFITEMS):

<Window x:Class="TestProject.MainWindow" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:Test="clr-namespace:TestProject" 
      Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition></RowDefinition>    
      <RowDefinition></RowDefinition> 
     </Grid.RowDefinitions> 
     <Test:UserControlTest Grid.Row="0" ItemsList="{Binding Path=ListOfItems}" /> 
     <Button Grid.Row="1" Content="AddItems" Click="Button_Click" /> 
    </Grid> 
</Window> 

而且我已經初始化的窗口中的datacontext代碼隱藏到視圖模型中。問題是綁定永遠不會發生,set屬性永遠不會調用依賴項屬性。我在這裏錯過了什麼嗎?

回答

9

那些getter和setter永遠不會被綁定系統調用(因此你不應該在那裏放置額外的代碼)。該屬性可能正在設置,但除非您在用戶控件的聲明中執行了任何操作,否則不會顯示任何內容。例如

<UserControl Name="control" ...> 
    <ItemsControl ItemsSource="{Binding ItemsList, ElementName=control}" /> 
</UserControl> 
+0

邦正在發生什麼事情。因爲我不能把代碼放在setter中,任何想法如何識別我的列表是否被更改並執行一些代碼? – 2012-02-05 06:48:16

+0

@AabidAli:您可以使用['ObservableCollection'](http://msdn.microsoft.com/en-us/library/ms668604.aspx)在更改時觸發事件,但不確定您嘗試執行的操作... – 2012-02-05 06:56:45

+0

@ HB我的意思是依賴屬性的變化。 Np我知道了,你只需要在初始化dp時添加一個Property Metadata來處理propertychanged。感謝您的幫助 – 2012-02-05 07:50:41