[英]How to add custom controls in WPF using MVVM and DataTemplate?
我基本上是在使用此代码,并且已成功将CheckBox
es(而不是示例中的ComboBox
)添加到View
。 但是,问题是我希望能够自定义(不同的Content
,binding等)那些CheckBox
。 现在,当我添加一个CheckBox
它会添加在DataTemplate
定义的默认CheckBox
。
DataTemplate
:
<DataTemplate DataType="{x:Type local:CurrencyViewModel}">
<StackPanel Orientation="Vertical">
<CheckBox Content="Default"/>
</StackPanel>
</DataTemplate>
CurrencyViewModel
程序未使用此处的代码,我不确定为什么,但是我很确定这是问题所在
class CurrencyViewModel : INotifyPropertyChanged
{
public CurrencyViewModel(ICurrency currency)
{
CheckBox currencyCheckBox = new CheckBox()
{
Content = currency.Name,
};
OnPropertyChanged("CurrenciesList");
}
MainViewModel
:
public MainViewModel()
{
foreach (ICurrency currencyin GetAllCurrencies())
{
CurrenciesList.Add(new CurrencyViewModel(currency));
}
}
private ObservableCollection<CurrencyViewModel> _CurrenciesList = new ObservableCollection<CurrencyViewModel>();
public ObservableCollection<CurrencyViewModel> CurrenciesList
{
get
{ return _CurrenciesList; }
set
{
_CurrenciesList = value;
OnPropertyChanged("CurrenciesList");
}
}
您不应该将View
对象放入ViewModel
-这会破坏模式的意图(将业务逻辑与表示分离)。 应该在View
通过Binding
, DataTemplates
, Triggers
等基于ViewModel
包含的状态,类型或数据来选择Checkbox
/ Combobox
。
我将重新评估您的设计,因为它与MVVM不兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.