我有一个绑定到用户对象集合的组合框。组合的 DisplayMemberPath 设置为“名称”,这是用户对象的属性。我还有一个文本框,它绑定到 ComboBox.SelectedItem 绑定的同一个对象。因此,当我更改 TextBox 中的文本时,我的更改会立即反映在组合中。只要 Name 属性未设置为空白,这正是我想要发生的。在这种情况下,我想替换一段通用文本,例如“{请提供姓名}”。不幸的是,我不知道该怎么做,所以在这方面的任何帮助将不胜感激!
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="340"
SizeToContent="Height"
WindowStartupLocation="CenterScreen"
ResizeMode="NoResize">
<StackPanel>
<TextBlock Text="ComboBox:" />
<ComboBox SelectedItem="{Binding SelectedUser}"
DisplayMemberPath="Name"
ItemsSource="{Binding Users}" />
<TextBlock Text="TextBox:"
Margin="0,8,0,0" />
<TextBox Text="{Binding SelectedUser.Name, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
public class ViewModel : INotifyPropertyChanged
{
private List<User> users;
private User selectedUser;
public event PropertyChangedEventHandler PropertyChanged;
public List<User> Users
{
get
{
return users;
}
set
{
if (users == value)
return;
users = value;
RaisePropertyChanged("Users");
}
}
public User SelectedUser
{
get
{
return selectedUser;
}
set
{
if (selectedUser == value)
return;
selectedUser = value;
RaisePropertyChanged("SelectedUser");
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class User
{
public string Name { get; set; }
}