【发布时间】:2015-11-11 21:44:48
【问题描述】:
我在 UserControl 中有一个 TextBox,它绑定到 MainWindow 的 ViewModel 中的一个属性。
现在,当我在文本框中键入内容时,它会更新视图模型中的属性,但如果我在后面的代码中更改文本框的文本,则视图模型属性不会更新。
实际上,文本框是从我单击按钮时打开的 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();
}
视图模型:
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
}
【问题讨论】:
-
只是好奇:我不知道“[CallerMemberName]”这个短语。那是来自 vs 版本 > 2010 的一些神奇的编译器吗?
-
@Udontknow 它是在 .NET 4.5 中引入的,基本上在编译时传递调用成员的名称。所以它非常适合实施 INPC。见MSDN。