繁体   English   中英

如何使用MVVM和DataTemplate在WPF中添加自定义控件?

[英]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通过BindingDataTemplatesTriggers等基于ViewModel包含的状态,类型或数据来选择Checkbox / Combobox

我将重新评估您的设计,因为它与MVVM不兼容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM