gpt4 book ai didi

c# - 更改 TextBox 文本时 ViewModel 属性未更新

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:04 25 4
gpt4 key购买 nike

我在 UserControl 中有一个 TextBox,它绑定(bind)到 MainWindow 的 ViewModel 中的一个属性。

现在,当我在文本框中键入内容时,它会更新 View 模型中的属性,但如果我在后面的代码中更改文本框的文本, View 模型属性不会更新。

实际上,文本框是从我单击按钮时打开的 FileDialog 中获取值的,因此文本框是从后面的代码中获取其文本的。

用户控件 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>

背后的UserControl代码

private void ButtonRun_OnClick(object sender, RoutedEventArgs e)
{
TextBoxFileOrFolder.Text = "FileName" + new Random().Next();
}

View 模型:

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
}

最佳答案

but if I change Textbox's text in code behind, the viewmodel property isn't updating.

那是因为如果您在代码隐藏中设置文本框的 Text 属性,您将覆盖绑定(bind)。因此,当您更新 View 时,指向您的 View 模型的链接已经消失,因此没有任何东西可以更新它。而且,当 View 模型更新值时, View 也不会更新。

要解决这个问题,只需不要在代码隐藏中设置具有绑定(bind)的属性。

与其在代码隐藏中处理按钮事件并更新 View ,不如将按钮命令绑定(bind)到 View 模型并更新 View 模型中的 FolderOrFileName

关于c# - 更改 TextBox 文本时 ViewModel 属性未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081153/

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