我在 UserControl 中有一个 TextBox,它绑定到 MainWindow 的 ViewModel 中的一个属性。
现在,当我在 Textbox 中输入内容时,它会更新 viewmodel 中的属性,但是如果我在后面的代码中更改 Textbox 的文本,则 viewmodel 属性不会更新。
实际上,文本框正在从 FileDialog 获取值,当我单击按钮时会打开该值,因此 Textbox 正在从后面的代码中获取其文本。
用户控件 XAML:
<StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Left">
<TextBox x:Name="TextBoxFileOrFolder" Text="{Binding FolderOrFileName}" Grid.Row="1" Width="200" Height="100" HorizontalAlignment="Left"></TextBox>
<Button x:Name="ButtonRun" Content="Run" Click="ButtonRun_OnClick" Width="200" Height="100" Margin="10"></Button>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
背后的用户控制代码
private void ButtonRun_OnClick(object sender, RoutedEventArgs e)
{
TextBoxFileOrFolder.Text = "FileName" + new Random().Next();
}
Run Code Online (Sandbox Code Playgroud)
视图模型:
public class MainViewModel: INotifyPropertyChanged
{
public MainViewModel()
{ }
private string folderOrFileName;
public string FolderOrFileName
{
get { return folderOrFileName; }
set
{
if (folderOrFileName!=value)
{
folderOrFileName = value;
RaisePropertyChanged();
}
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the property changed.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
# endregion
}
Run Code Online (Sandbox Code Playgroud)
但是如果我在后面的代码中更改 Textbox 的文本,则 viewmodel 属性不会更新。
这是因为如果您Text在代码隐藏中设置文本框的属性,则会覆盖绑定。所以当你更新视图时,你的视图模型的链接消失了,所以没有什么可以更新它。而且,当视图模型更新值时,视图也不会更新。
要解决此问题,只需不要在代码隐藏中设置具有绑定的属性。
与其在代码隐藏中处理按钮事件并更新视图,不如将按钮命令绑定到视图模型并更新FolderOrFileName视图模型中的 。