[英]Caliburn Micro MVVM INotifyPropertyChange
因此,我使用的是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吗? 但是,如果我更新第二个文本框(具有绑定的SelectedUser.FirstName的文本框)中的值,则确实会更新数据网格,
有任何想法吗?? 基本上,我只想在文本框中的值通过验证时更新datagrid。 假设我不想编辑datagrid本身中的值。
令我发狂,我知道它一定是通过通知的方式来实现的,但是我无法使其正常工作,并且对于c#和MVVM和WPF来说还很陌生,任何帮助将不胜感激。 谢谢
您需要对FirstName而不是SelectedUser进行NotifyOfPropertyChange。 最好您在FirstName setter中执行此操作。
因此,我实现IDataError的方式是错误的,您无需在else语句中设置值。 我应该实现它的方式。
应该在我的模型中而不是在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的帮助,指出了正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.