gpt4 book ai didi

c# - 在数据网格中编辑当前选定的项目

转载 作者:行者123 更新时间:2023-11-30 15:35:17 26 4
gpt4 key购买 nike

嘿,

我正在使用 MVVM 创建简单的应用程序,偶然发现了一个我发现很难解决的问题。在我的应用程序中,我有数据网格和几个控件来编辑数据网格中当前选定的项目。在我的 ViewModel 中,我有 CurrentSequence 属性,其中包含 ColorSettingsSequencesSequence 对象(这些对象的集合用作数据网格的 DataContext)。

这是 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");
}
}

这很好用,但是当我想添加验证时,问题就来了。我想分别验证 StartTempEndTemp 并给出不同的错误。我将如何分解 ColorSettingsSequencesSequence 对象,以便如果我编辑一个值它也会在数据网格中更新,绑定(bind)也仍然有效?

这是我的尝试,我创建了 2 个新属性并向它们添加了验证:

private String _currentSequenceStartTemp;
public String CurrentSequenceStartTemp
{
get
{
return _currentSequenceStartTemp;
}
set
{
this._currentSequenceStartTemp = value;
CurrentSequence.StartTemp = value;
RaisePropertyChanged("CurrentSequenceStartTemp");
Validator.Validate(() => CurrentSequenceStartTemp);
ValidateCommand.Execute(null);
}
}

private String _currentSequenceEndTemp;
public String CurrentSequenceEndTemp
{
get
{
return _currentSequenceEndTemp;
}
set
{
this._currentSequenceEndTemp = value;
CurrentSequence.EndTemp = value;
RaisePropertyChanged("CurrentSequenceEndTemp");
Validator.Validate(() => CurrentSequenceEndTemp);
ValidateCommand.Execute(null);
}
}

我只是将 TextBoxes 绑定(bind)到这些值,而不是直接将它们绑定(bind)到 CurrentSequence。我还在 setter 中添加了设置 CurrentSequence 值,并希望我的更改将一直推回原始集合并在数据网格中进行更改。那没有发生..当 CurrentSequence 改变时,我也会改变这些属性的值:

private ColorSettingsSequencesSequence _currentSequence;
public ColorSettingsSequencesSequence CurrentSequence
{
get
{
return this._currentSequence;
}
set
{
this._currentSequence = value;
RaisePropertyChanged("CurrentSequence");
if (value != null)
{
CurrentSequenceStartTemp = value.StartTemp;
CurrentSequenceEndTemp = value.EndTemp;
}
else
{
CurrentSequenceStartTemp = String.Empty;
CurrentSequenceEndTemp = String.Empty;
}
}
}

最佳答案

我已经重现了你的问题。但是我找不到任何问题。一切正常。

  • 分别验证 StartTempEndTemp
  • 如果更新了一个值,则数据网格也应该更新

所以我在项目中解决了以上两个问题。

结果

enter image description here

将起始温度更改为 40 后,datagrid 值也发生了变化。

enter image description here

让我们在开始温度文本框中创建一个错误。

enter image description here

现在是另一个

enter image description here

您现在可以看到这两个属性都分别进行了验证。

这是我创建的项目。

项目结构

enter image description here

ViewModelBase 类

public class ViewModelBase : INotifyPropertyChanged
{
#region Implementation of INotifyPropertyChanged

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}

protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, args);
}

#endregion
}

ColorSettingsSequences序列类

public class ColorSettingsSequencesSequence : ViewModelBase, IDataErrorInfo
{
#region Declarations

private string startColor;
private string startTemperature;
private string endTemperature;

#endregion

#region Properties

/// <summary>
/// Gets or sets the start color.
/// </summary>
/// <value>
/// The start color.
/// </value>
public string StartColor
{
get
{
return this.startColor;
}
set
{
this.startColor = value;
OnPropertyChanged("StartColor");
}
}

/// <summary>
/// Gets or sets the start temperature.
/// </summary>
/// <value>
/// The start temperature.
/// </value>
public string StartTemperature
{
get
{
return this.startTemperature;
}
set
{
this.startTemperature = value;
OnPropertyChanged("StartTemperature");
}
}

/// <summary>
/// Gets or sets the end temperature.
/// </summary>
/// <value>
/// The end temperature.
/// </value>
public string EndTemperature
{
get
{
return this.endTemperature;
}
set
{
this.endTemperature = value;
OnPropertyChanged("EndTemperature");
}
}

#endregion

/// <summary>
/// Gets an error message indicating what is wrong with this object.
/// </summary>
/// <returns>An error message indicating what is wrong with this object. The default is an empty string ("").</returns>
public string Error
{
get
{
return "";
}
}

/// <summary>
/// Gets the error message for the property with the given name.
/// </summary>
/// <param name="columnName">Name of the column.</param>
/// <returns></returns>
public string this[string columnName]
{
get
{
if (columnName.Equals("StartTemperature"))
{
if (string.IsNullOrEmpty(this.StartTemperature))
{
return "Please enter a start temperature";
}
}

if (columnName.Equals("EndTemperature"))
{
if (string.IsNullOrEmpty(this.EndTemperature))
{
return "Please enter a end temperature";
}
}

return "";
}
}
}

主视图模型

public class MainViewModel : ViewModelBase
{
#region Declarations

private ColorSettingsSequencesSequence currentSequence;
private ObservableCollection<ColorSettingsSequencesSequence> colorSettingsSequences;

#endregion

#region Properties

/// <summary>
/// Gets or sets the current sequence.
/// </summary>
/// <value>
/// The current sequence.
/// </value>
public ColorSettingsSequencesSequence CurrentSequence
{
get
{
return this.currentSequence;
}
set
{
this.currentSequence = value;
OnPropertyChanged("CurrentSequence");
}
}

/// <summary>
/// Gets or sets the color settings sequences.
/// </summary>
/// <value>
/// The color settings sequences.
/// </value>
public ObservableCollection<ColorSettingsSequencesSequence> ColorSettingsSequences
{
get
{
return this.colorSettingsSequences;
}
set
{
this.colorSettingsSequences = value;
OnPropertyChanged("ColorSettingsSequences");
}
}

#endregion

#region Commands

#endregion

#region Constructors

/// <summary>
/// Initializes a new instance of the <see cref="MainViewModel" /> class.
/// </summary>
public MainViewModel()
{
this.ColorSettingsSequences = new ObservableCollection<ColorSettingsSequencesSequence>();

ColorSettingsSequencesSequence sequence1 = new ColorSettingsSequencesSequence();
sequence1.StartColor = "Blue";
sequence1.StartTemperature = "10";
sequence1.EndTemperature = "50";
ColorSettingsSequences.Add(sequence1);

ColorSettingsSequencesSequence sequence2 = new ColorSettingsSequencesSequence();
sequence2.StartColor = "Red";
sequence2.StartTemperature = "20";
sequence2.EndTemperature = "60";
ColorSettingsSequences.Add(sequence2);

ColorSettingsSequencesSequence sequence3 = new ColorSettingsSequencesSequence();
sequence3.StartColor = "Yellow";
sequence3.StartTemperature = "30";
sequence3.EndTemperature = "70";
ColorSettingsSequences.Add(sequence3);

this.CurrentSequence = sequence1;

}

#endregion

#region Private Methods

#endregion
}

主窗口.xaml (XAML)

<Window x:Class="DataGridValidation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">

<Window.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>

<Grid Name="mainGrid">

<Grid.RowDefinitions>
<RowDefinition Height="149" />
<RowDefinition Height="73" />
<RowDefinition Height="123" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="249*" />
</Grid.ColumnDefinitions>

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding ColorSettingsSequences}"
SelectedItem="{Binding CurrentSequence}"
IsReadOnly="True">

<DataGrid.Columns>
<DataGridTextColumn Header="Start Color" Binding="{Binding StartColor}" />
<DataGridTextColumn Header="End Color" Binding="{Binding StartTemperature}" />
<DataGridTextColumn Header="End Color" Binding="{Binding EndTemperature}" />
</DataGrid.Columns>

</DataGrid>

<StackPanel Grid.Column="0" Grid.Row="1">
<Grid>
<Label Content="Start temperature (°C)"
Height="28"
HorizontalAlignment="Left"
x:Name="lblSeqStartTemp"
VerticalAlignment="Top" />
<TextBox Height="23"
Margin="10,28,10,0"
x:Name="tbSeqStartTemp"
VerticalAlignment="Top"
Text="{Binding Path=CurrentSequence.StartTemperature, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
</Grid>
</StackPanel>
<StackPanel Grid.Row="2" Margin="0,0,0,43">
<Grid>
<Label Content="End temperature (°C)"
HorizontalAlignment="Left"
VerticalAlignment="Top" />
<TextBox Height="23"
Margin="10,28,10,0"
x:Name="tbSeqEndTemp"
VerticalAlignment="Top"
Text="{Binding Path=CurrentSequence.EndTemperature, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
</Grid>
</StackPanel>
</Grid>
</Window>

MainWindow.xaml.cs(代码隐藏文件)

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
mainGrid.DataContext = new MainViewModel();
}
}

关于c# - 在数据网格中编辑当前选定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15173762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com