如何使用 MVVM 和 DataTemplate 在 WPF 中添加自定义控件?
How to add custom controls in WPF using MVVM and DataTemplate?
我基本上是在使用 this 代码,并且成功地将 CheckBox
es(而不是示例中的 ComboBox
)添加到我的 View
。然而,问题是我希望能够自定义(不同的 Content
、绑定等)那些 CheckBox
es。现在,当我添加 CheckBox
时,它会添加在我的 DataTemplate
.
中定义的默认值
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
- 它破坏了模式的意图(将业务逻辑与表示分离)。 Checkbox
/Combobox
应根据您的 ViewModel
通过 Binding
、DataTemplates
包含的状态、类型或数据在 View
中做出选择, Triggers
, 等等
我会重新评估您的设计,因为它与作为模式的 MVVM 不兼容。
我基本上是在使用 this 代码,并且成功地将 CheckBox
es(而不是示例中的 ComboBox
)添加到我的 View
。然而,问题是我希望能够自定义(不同的 Content
、绑定等)那些 CheckBox
es。现在,当我添加 CheckBox
时,它会添加在我的 DataTemplate
.
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
- 它破坏了模式的意图(将业务逻辑与表示分离)。 Checkbox
/Combobox
应根据您的 ViewModel
通过 Binding
、DataTemplates
包含的状态、类型或数据在 View
中做出选择, Triggers
, 等等
我会重新评估您的设计,因为它与作为模式的 MVVM 不兼容。