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

时间:2015-05-13 14:56:57

标签: c# wpf 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");
    }
}

1 个答案:

答案 0 :(得分:1)

你不应该在View中放置ViewModel个对象 - 它会打破模式的意图(将业务逻辑与表示分离)。 Checkbox / Combobox选项应根据View ViewModel Binding DataTemplates所包含的州,类型或数据在Triggers中进行选择,FileWriter writer = new FileWriter( "DonneesPings1.csv" ); FileWriter writer2 = new FileWriter( "DonneesPings2.csv" ); writer.write( "X,Y\n" ); int limit = 0; for (XtfPing ping : xtf.getPings()) { if ( limit < 10000 ) { writer.write( Double.toString( ping.x ) ); writer.write( "," ); writer.write( Double.toString( ping.y ) ); writer.write( "\n" ); } else { writer2.write( Double.toString( ping.x ) ); writer2.write( "," ); writer2.write( Double.toString( ping.y ) ); writer2.write( "\n" ); } limit++; } writer.close(); 等。

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