2010-06-28 63 views
0

我的業務層中有一個對象(讓我們把它叫做Car來做例子),並且我創建了一個UserControl(CarIcon)。用戶控件的屬性是一個Car對象,當Car對象被設置時,它調用一個方法來配置用戶控件的各種屬性。使用DependencyProperties和後臺對象設計WPF用戶控件

現在我重寫它以使用依賴屬性,以便我可以使用數據模板並在運行時將後備Car對象綁定到CarIcon用戶控件。理想情況下,我想將該對象綁定到用戶控件,並讓用戶控件自動更新其顯示。

似乎沒有設置依賴項屬性,並且應用程序顯示空白圖標(因爲沒有後備對象就沒有數據顯示)。我是否正確地綁定了一些東西?

也是這是一個合理的方法(考慮到我不想實現一個完整的MVVM的簡單控制)?

綁定車到CarIcon在XAML

<ItemsControl Name="m_itemsControl" Focusable="false" 
    pixellabs:AnimatingTilePanel.ItemHeight="100" pixellabs:AnimatingTilePanel.ItemWidth="300"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <pixellabs:AnimatingTilePanel Width="300" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <sample:CarIcon CurrentCar="{Binding}" /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

代碼依賴屬性

public Car CurrentCar { 
     get { return (Car)GetValue(CarProperty); } 
     set { SetValue(CarProperty, value); } 
    } 

    public static readonly DependencyProperty CarProperty = 
     DependencyProperty.Register( 
      "CurrentCar", 
      typeof(Car), 
      typeof(CarIcon), 
      new UIPropertyMetadata()); 

回答

0

變化的第一個參數的屬性名稱(CurrentCar而不是汽車)。你還應該提供一些默認值,例如null或new Car()

public static readonly DependencyProperty CarProperty = 
     DependencyProperty.Register( 
      "CurrentCar", 
      typeof(Car), 
      typeof(CarIcon), 
      new UIPropertyMetadata(new Car())); 
+0

好的,修正了,但我仍然沒有得到綁定。 ObservableCollection我是綁定項目源的作品,我得到了四個空白圖標顯示,但每個數據模板中的單個綁定似乎不起作用。另外,如果我在DP.Register中初始化新的Car(),那麼它是否是靜態的?爲了使它不是靜態的,你必須在我想的cctor中初始化它。 – vfilby 2010-06-28 19:45:57

+0

請爲您的數據模板問題創建另一個問題。默認值用於CurrentCar屬性,直到它被調用CurrentCar set屬性或通過數據綁定的其他代碼更改爲止。 – 2010-06-28 20:00:16