使用MVVM中的CollectionControl生成动态按钮

时间:2019-06-25 09:22:47

标签: c# wpf mvvm collections controls

在MVVM设计模式项目中,我有一个视图,只有很少的控件绑定到VIEWMODEL,现在我需要使用Collection Control从代码动态添加Buttons。我怎么做?? XAML和ViewModel分别是什么?

这是ViewModel代码。

class ViewModel : INotifyPropertyChanged
{
    private double resultantValue;
    public double ResultantValue
    {
        get { return resultantValue; }
        set { resultantValue = value; OnPropertyChanged(); }
    }

    private double operandOne;
    public double OperandOne
    {
        get { return operandOne; }
        set { operandOne = value; OnPropertyChanged(); }
    }

    private double operandTwo;
    public double OperandTwo
    {
        get { return operandTwo; }
        set { operandTwo = value; OnPropertyChanged(); }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

        }
    }
}

这是MainWindow.xaml

<Window x:Class="TempMVVM.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TempMVVM"
    xmlns:vm="clr-namespace:TempMVVM.ViewModel"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>
    <vm:ViewModel x:Key="ViewModel"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource ViewModel}}">
    <Border Padding="20">
        <StackPanel>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <StackPanel Margin="20 10 20 0" Grid.Column="0">
                    <Label>OperandOne</Label>
                    <TextBox Text="{Binding OperandOne}" />
                </StackPanel>
                <StackPanel Margin="0 10 20 0" Grid.Column="1">
                    <Label>OperandTwo</Label>
                    <TextBox Text="{Binding OperandTwo}" />
                </StackPanel>
            </Grid>

            <StackPanel Margin="20 10 10 20">
                <Label>Result</Label>
                <TextBox Text="{Binding ResultantValue}"  />
            </StackPanel>
        </StackPanel>
    </Border>
</Grid>

0 个答案:

没有答案