C# 使用DependencyProperties和备份对象设计WPF用户控件
我的业务层中有一个对象(例如,为了方便起见,让我们称之为Car),我创建了一个UserControl(CarIcon)。用户控件有一个属性,它是一个Car对象,当设置Car对象时,它调用一个方法来配置用户控件的各种属性 现在我正在重写它以使用依赖属性,这样我就可以使用数据模板并在运行时将backing Car对象绑定到CarIcon用户控件。理想情况下,我希望将对象绑定到用户控件,并让用户控件自动更新其显示 似乎没有设置dependency属性,应用程序显示的是空白图标(因为没有支持对象,就没有要显示的数据)。我把东西装订错了吗 这也是一种合理的方法(考虑到我不想为一个简单的控件实现一个完整的MVVM) 用xaml将汽车绑定到CarIcon上C# 使用DependencyProperties和备份对象设计WPF用户控件,c#,wpf,dependency-properties,C#,Wpf,Dependency Properties,我的业务层中有一个对象(例如,为了方便起见,让我们称之为Car),我创建了一个UserControl(CarIcon)。用户控件有一个属性,它是一个Car对象,当设置Car对象时,它调用一个方法来配置用户控件的各种属性 现在我正在重写它以使用依赖属性,这样我就可以使用数据模板并在运行时将backing Car对象绑定到CarIcon用户控件。理想情况下,我希望将对象绑定到用户控件,并让用户控件自动更新其显示 似乎没有设置dependency属性,应用程序显示的是空白图标(因为没有支持对象,就没有
<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>
将第一个参数更改为属性名称(CurrentCar而不是Car)。您还应该提供一些默认值,例如null或newcar()
好的,已经修好了,但是我还没有拿到装订。我正在将项目源绑定到的ObservableCollection可以工作,并且我会显示四个空白图标,但是每个数据模板中的单个绑定似乎不起作用。另外,如果我在DP.寄存器中初始化new Car(),这会使它成为静态的吗?要使其非静态,您必须在我认为的cctor中对其进行初始化。请针对您的数据模板问题创建另一个问题。默认值用于CurrentCar属性,直到其他调用CurrentCar set属性的代码或通过数据绑定对其进行更改。
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() );
public static readonly DependencyProperty CarProperty =
DependencyProperty.Register(
"CurrentCar",
typeof(Car),
typeof(CarIcon),
new UIPropertyMetadata(new Car()));