使用相同的控件在datagrid中添加和编辑项目

时间:2013-02-12 20:24:40

标签: c# wpf mvvm datagrid

平,

我在我的wpf应用程序中使用MVVM。我有DataGrid显示的项目列表,我已经在我的ViewModel中将SelectedItem绑定到CurrentSequence。当CurrentSequence更改该对象的属性时,会在其他控件中显示以进行编辑。

继承我的xaml:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=ColorSettingsSequences}"
                  SelectedItem="{Binding Path=CurrentSequence, Mode=TwoWay}">
    .... more things here ...
</DataGrid>

<StackPanel Grid.Column="0" Grid.Row="0">
    <Grid>
        <Label Content="Start temperature (°C)" Height="28" HorizontalAlignment="Left" x:Name="lblSeqStartTemp" VerticalAlignment="Top" />
        <TextBox Height="23" Margin="0,28,10,0" x:Name="tbSeqStartTemp" VerticalAlignment="Top" Text="{Binding Path=CurrentSequence.StartTemp}" />
    </Grid>
    <Grid>
        <Label Content="Start color" Height="28" HorizontalAlignment="Left" x:Name="lblSeqHue" VerticalAlignment="Top" />
        <xctk:ColorPicker Margin="0,28,10,0" x:Name="clrpSeqHue" SelectedColor="{Binding Path=CurrentSequence.StartHue, Converter={StaticResource hueToColor}, ConverterParameter=False}" ShowStandardColors="False" />
    </Grid>
</StackPanel>
<StackPanel Grid.Column="1" Grid.Row="0">
    <Grid>
        <Label Content="End temperature (°C)" Height="28" HorizontalAlignment="Left" x:Name="lblSeqEndTemp" VerticalAlignment="Top" />
        <TextBox Height="23" Margin="0,28,10,0" x:Name="tbSeqEndTemp" VerticalAlignment="Top" Text="{Binding Path=CurrentSequence.EndTemp}" />
    </Grid>
    <Grid>
        <Label Content="End color" Height="28" HorizontalAlignment="Left" x:Name="lblSeqEndHue" VerticalAlignment="Top" />
        <xctk:ColorPicker Margin="0,28,10,0" x:Name="clrpSeqEndHue" SelectedColor="{Binding Path=CurrentSequence.EndHue, Converter={StaticResource hueToColor}, ConverterParameter=False}" ShowStandardColors="False" />
    </Grid>
</StackPanel>

代码:

private ColorSettingsSequencesSequence _currentSequence;
public ColorSettingsSequencesSequence CurrentSequence
{
    get
    {
        return this._currentSequence;
    }
    set
    {
        this._currentSequence = value;
        OnPropertyChanged("CurrentSequence");
    }
}

现在的问题是,我怎么能添加一个按钮来保存更改或添加一个全新的项目。我知道如何做一个或另一个,但2与相同的控件一起...

1 个答案:

答案 0 :(得分:0)

您可以在视图模型上创建一个名为CurrentSequenceEdit的ColorSettingsSequencesSequence类型的属性,并且可以在更改选择时设置此对象的值。

然后单击添加按钮,您可以创建一个新的ColorSettingsSequencesSequence对象,并将其设置为CurrentSequenceEdit的值。

通常在新对象上,您将拥有未设置的ID或设置为负数,您可以在“保存”命令中使用该数字来确定是否需要将其添加到网格中。