通过INotifyPropertyChanged写入文本框不工作
本文关键字:工作 文本 INotifyPropertyChanged 通过 | 更新日期: 2023-09-27 18:04:18
我有一个问题,一个属性调用INotifyPropertyChanged事件。我创建了一个简单的概念WPF程序,它试图通过一个按钮来写入一个文本框,该按钮调用一个函数来更新属性(ViewModel1StringProperty)。该属性被绑定到文本框,并且该属性调用一个INotifyPropertyChanged事件。我已经为文本框添加了这个text属性:
Text="{Binding ViewModel1StringProperty, UpdateSourceTrigger=PropertyChanged}"
但是,当单击按钮时,文本框仍然没有更新。需要注意的一点是,按钮调用iccommand,然后最终通过函数调用(TestFunction1)更新属性。我相信这个命令是正确地绑定到按钮,但我不确定。
对此问题的任何见解都将非常感谢。
ViewModel代码:
namespace WpfApplicationOnPropertyChanged.ViewModel
{
class ViewModel1 : INotifyPropertyChanged
{
#region Fields
string _viewModel1StringProperty;
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#region Properties
public string ViewModel1StringProperty
{
get
{
return _viewModel1StringProperty;
}
set
{
_viewModel1StringProperty = value;
NotifyPropertyChanged("ViewModel1StringProperty");
}
}
#endregion
#region Commands
public ICommand ViewModelICommandField1
{
get
{
return new ViewModelICommand(TestFunction1);
}
}
#endregion
#region Functions
private void TestFunction1()
{
ViewModel1StringProperty = "Test1'n";
}
#endregion
}
}
视图代码:
namespace WpfApplicationOnPropertyChanged.View
{
/// <summary>
/// Interaction logic for View1.xaml
/// </summary>
public partial class View1 : UserControl
{
#region Fields
ViewModel1 _viewModel1 = new ViewModel1();
#endregion
public View1()
{
InitializeComponent();
this.DataContext = _viewModel1;
}
}
}
XAML代码: <UserControl x:Class="WpfApplicationOnPropertyChanged.View.View1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml /presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplicationOnPropertyChanged.View"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBox Name="textBox1" HorizontalAlignment="Left" Height="89" Margin="58,62,0,0" Text="{Binding ViewModel1StringProperty, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" VerticalAlignment="Top" Width="181"/>
<Button Content="Button1" Command="{Binding ViewModel1ICommandField1}" HorizontalAlignment="Left" Margin="106,205,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</UserControl>
ICommand代码:
namespace WpfApplicationOnPropertyChanged.ViewModel
{
class ViewModelICommand : ICommand
{
private Action _action;
public ViewModelICommand(Action action)
{
_action = action;
}
public void Execute(object parameter)
{
_action();
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged
{
add { }
remove { }
}
}
}
在XAML中,您已经将按钮命令绑定到ViewModel1ICommandField1
,但在视图模型中,它的名称是ViewModelICommandField1
。
请重新命名它们以便它们匹配,这样您将得到正确的行为