User オブジェクトの Collection にバインドされた ComboBox があります。コンボの DisplayMemberPath は、User オブジェクトのプロパティである「Name」に設定されます。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; }
}