C# WPF-组合框选择更改=>;更改文本框绑定
我有一个组合框和一个文本框。文本框绑定到我的ViewModel中的“默认”属性 我试图实现的是,当我更改ComboBox中的值时,TextBox的属性将更改为另一个属性C# WPF-组合框选择更改=>;更改文本框绑定,c#,wpf,data-binding,listbox,C#,Wpf,Data Binding,Listbox,我有一个组合框和一个文本框。文本框绑定到我的ViewModel中的“默认”属性 我试图实现的是,当我更改ComboBox中的值时,TextBox的属性将更改为另一个属性 <ComboBox SelectedIndex="0" Name="ComboBox1"> <ComboBoxItem> Messages1 </ComboBoxItem> <ComboBoxItem> Messages2
<ComboBox SelectedIndex="0" Name="ComboBox1">
<ComboBoxItem>
Messages1
</ComboBoxItem>
<ComboBoxItem>
Messages2
</ComboBoxItem>
</ComboBox>
<TextBox Text="{Binding Messages1}" IsReadOnly="True" VerticalScrollBarVisibility="Visible" AcceptsReturn="True" Name="LogTextBox" />
信息1
信息2
我想将文本框的绑定更改为Messages2。我尝试了很多东西,但似乎都不管用
有一个简单的解决方案吗?以前有人问过,最好、最干净的解决方案,但不是那么通用的解决方案,就是创建几个文本框,除了相关的文本框外,这些文本框将折叠可见。更新组合框所选项目时,请更新文本框的可见性绑定。假设您已经实现了
INotifyPropertyChanged
,您可以这样做:
代码隐藏:
public string Message1
{
get { return (string)GetValue(Message1Property); }
set { SetValue(Message1Property, value); }
}
// Using a DependencyProperty as the backing store for Message1. This enables animation, styling, binding, etc...
public static readonly DependencyProperty Message1Property =
DependencyProperty.Register("Message1", typeof(string), typeof(MainWindow), new PropertyMetadata(string.Empty));
public string Message2
{
get { return (string)GetValue(Message2Property); }
set { SetValue(Message2Property, value); }
}
// Using a DependencyProperty as the backing store for Message2. This enables animation, styling, binding, etc...
public static readonly DependencyProperty Message2Property =
DependencyProperty.Register("Message2", typeof(string), typeof(MainWindow), new PropertyMetadata(string.Empty));
//an array of properties as combobox.Items
public DependencyProperty[] AllowedProperties
{
get
{
return new DependencyProperty[] { Message1Property, Message2Property };
}
}
//selected property as combobox.selectedItem
DependencyProperty _chosenProperty;
public DependencyProperty ChosenProperty
{
get
{
return _chosenProperty;
}
set
{
_chosenProperty = value;
OnPropertyChanged("ChosenValue");
}
}
//value of the selected property as textbox.text.
public string ChosenValue
{
get
{
return ChosenProperty == null ? string.Empty : (string)GetValue(ChosenProperty);
}
}
XAML:
ByListBox
你是说ComboBox
?是的,我是说ComboBox。。。我不知道为什么我脑子里有列表框。。。我改了谢谢你。这是可行的,但我希望它更容易实现。我会按照“本·科恩”的建议去做。我想避免他的解决方案,但这比这更容易。我同意,我认为没有任何简单的解决方案。“Ben Cohen”所建议的是一种更好的方式,我主要发布这个答案是为了表明还有其他选择。我有同样的想法,我也有过类似的想法,但我认为以某种方式更改绑定会更简单。我会将你的答案标记为正确,因为这比更改绑定要简单得多。
<ComboBox ItemsSource="{Binding AllowedProperties}"
SelectedItem="{Binding ChosenProperty}"
>
</ComboBox>
<TextBlock Text="{Binding ChosenValue}"/>