开发者

How to enable wpf controls through data binding on a selected item from a combo box

开发者 https://www.devze.com 2023-03-20 23:19 出处:网络
I am looking for a way where a control can be enable when an item from a combo box is selected. Is there a simple way through data binding when a user selects an item from a combo box that it 开发者_S

I am looking for a way where a control can be enable when an item from a combo box is selected. Is there a simple way through data binding when a user selects an item from a combo box that it 开发者_StackOverflow社区then enables another control to be used?


If you're using MVVM, you can bind the SelectedItem of the combobox to a property in your viewmodel.

Say this is your combobox:

<ComboBox ItemsSource="{Binding widgetlist}" SelectedItem="{Binding Path=selectedwidget, Mode=TwoWay}"></ComboBox>

And this is your control:

<DockPanel IsEnabled="{Binding controlenabled}">
    ...
</DockPanel>

Then in selectedwidget's setter, you can change the controlenabled property to False or True. Don't forget to notify that the controlenabled property changed (or if you want, make controlenabled a DependencyProperty.)

In summary, you've got 3 properties to bind to:

  • widgetlist, an ObservableCollection or some other collection that is the source for your combobox

  • selectedwidget, an item of that collection type that changes to whatever the combobox currently has selected

  • controlenabled, a bool that the other controls look at to decide if they are enabled/disabled.

Like many examples in MVVM, this way may require slightly more thought and code on the outset, but will be far more maintainable and scalable later. For example, say you want some more controls to also enable/disable themselves based on the same scenario. Piece of cake: add IsEnabled="{Binding controlenabled}"> to them.


Yes. You want to bind to IsEnabled in the target control which you want to dynamically enable or disable, and use a Value Converter to convert a matching string or item from the ComboBox to a true value for being enabled.

0

精彩评论

暂无评论...
验证码 换一张
取 消