所以我正在使用Cliburn Micro,我有一个Bindablecollection,让我们称之为用户。
public BindableCollection<UserModel> Users
{
get { return _users; }
set
{
_users = value;
NotifyOfPropertyChange(() => Users);
}
}
现在这链接到一个带有两列FirstName和LastName的数据网格在另一个面板中,数据网格的选定项目被设置
<DataGrid x:Name="AllUsers" SelectionMode="Single" Margin="5"
SelectionUnit="FullRow" AutoGenerateColumns="False"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserReorderColumns="False"
IsReadOnly="True" Style="{DynamicResource DataGridUsers}"
SelectedItem="{Binding Path=SelectedUser, Mode=TwoWay}"
cal:Message.Attach="[Event MouseDoubleClick] = [Action DoubleClickUser()]">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}" Width="*"/>
<DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
然后我创建了一个TextBoxFirstName,我只设置了值,如果它不为null
<DockPanel>
<Label x:Name="LabelFirstName" Width="80" HorizontalContentAlignment="Left" VerticalAlignment="Center" Foreground="#FFAD231F" FontFamily="Lucida Sans Unicode" FontSize="12" >First Name</Label>
<TextBox x:Name="TextBoxFirstName" Margin="0,0,5,0" Text="{Binding
UpdateSourceTrigger=PropertyChanged, Path=TextBoxFirstName,
ValidatesOnDataErrors=true, NotifyOnValidationError=true}"
HorizontalAlignment="Stretch" Height="23" TextAlignment="Center" TextWrapping="NoWrap" VerticalAlignment="Top" Style="{StaticResource RoundedTextBox}" FontFamily="Lucida Sans Unicode"/>
</DockPanel>
我对文本框的错误验证是,
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "TextBoxFirstName")
{
if (string.IsNullOrEmpty(TextBoxFirstName))
{
result = "Please enter a First Name";
}
else
{
SelectedUser.FirstName = TextBoxFirstName;
NotifyOfPropertyChange(() => SelectedUser);
}
}
return result;
}
}
现在我知道SelectedUser.FirstName被更新,好像我将另一个文本框数据绑定设置为SelectedUser.FirstName,它按预期更新,但是当我更改它时它没有更新Datagrid?但是,如果我更新secondtextbox(具有绑定SelectedUser.FirstName的那个)中的值,它确实更新了datagrid,
有任何想法吗??基本上我只想更新数据网格,如果文本框中的值通过验证。假设我不想编辑datagrid本身的值。
让我发疯,我知道它必须以它通知的方式,但我不能让它工作,而且我对c#和MVVM和WPF相当新,任何帮助都会非常感激。谢谢
您需要在FirstName而不是SelectedUser上使用NotifyOfPropertyChange。您最好在FirstName setter中执行此操作。
所以,我实现IDataError的方式是错误的,你不需要在else语句中设置值。 The way i should have implemented it.
应该在我的模型中使用它而不是在viewmodel中。
我的模型也是这样的,
namespace App.Models
{
public class ConfigModel : INotifyPropertyChanged
{
private bool _showConfig;
public event PropertyChangedEventHandler PropertyChanged;
public bool ShowConfig
{
get { return this._showConfig; }
set
{
this._showConfig = value;
this.OnPropertyChanged("ShowConfig");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
感谢Wes和Mark的帮助,指出我正确的方向。