WPF - ComboBox SelectionChanged =>更改TextBox绑定

时间:2015-06-28 07:35:29

标签: c# wpf data-binding listbox

我有一个ComboBox和一个TextBox。 TextBox绑定到我的ViewModel中的"默认" -property。

我想要完成的是当我更改ComboBox中的值时,TextBox的属性将更改为另一个属性。

<ComboBox SelectedIndex="0" Name="ComboBox1">
    <ComboBoxItem>
        Messages1
    </ComboBoxItem>
    <ComboBoxItem>
        Messages2
    </ComboBoxItem>
</ComboBox>

 <TextBox Text="{Binding Messages1}" IsReadOnly="True" VerticalScrollBarVisibility="Visible" AcceptsReturn="True" Name="LogTextBox" />

我想将TextBox的绑定更改为Messages2。我尝试过很多东西,但似乎没什么用。

有一个简单的解决方案吗?

2 个答案:

答案 0 :(得分:1)

以前曾经问过 - 最好也是最干净的解决方案,但不是那种通用的 - 正在创建几个文本框,除了相关文本框之外,它们将被折叠显示。更新组合框选定项目时,请更新文本框的可见性绑定。

答案 1 :(得分:1)

假设您已实施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:

    <ComboBox ItemsSource="{Binding AllowedProperties}" 
              SelectedItem="{Binding ChosenProperty}"
              >
    </ComboBox>
    <TextBlock Text="{Binding ChosenValue}"/>