undefined undefined - 1 month ago 19
C# Question

ComboBox databinding to window background

Very new to

WPF
and
c#
here. I'm interested in having a
ComboBox
with different color options that will update the window's
Background
when an option is selected.

I want to do this via
DataBinding
, but I'm a noob and can't get it right. This is what I have.

MainWindow.xaml

<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" Height="350" Width="525"
Background="{Binding SelectedValue,ElementName=combo,UpdateSourceTrigger=PropertyChanged}">
<StackPanel>
<ComboBox Name="combo">
<ComboBoxItem>lightcoral</ComboBoxItem>
<ComboBoxItem>khaki</ComboBoxItem>
</ComboBox>
</StackPanel>
</Window>


And the default
MainWindow.xaml.cs
(I haven't touched it since I created the project)

Thanks, let me know if you need any more info!

Answer

One possible way to achieve this is to put items of type string in your ComboBox, as opposed to ComboBoxItems:

<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" Height="350" Width="525"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Background="{Binding SelectedItem, ElementName=combo}">
    <ComboBox VerticalAlignment="Center" HorizontalAlignment="Center" x:Name="combo">
        <sys:String>Yellow</sys:String>
        <sys:String>Green</sys:String>
        <sys:String>Red</sys:String>
        <sys:String>Blue</sys:String>
    </ComboBox>
</Window>
  • Notice that I declared the xmlns:sys XAML Namespace that points to the System CLR namespace in the mscorlib.dll assembly. This is where the class System.String is defined, and you need that to be able to use the class in XAML.

  • Also notice that I'm binding to SelectedItem as opposed to SelectedValue, this is because your ComboBox does not have SelectedValuePath, and WPF doesn't have the notion of the SelectedValue because it does not know how to "retrieve the value" from each of it's items.

  • Also notice that UpdateSourceTrigger is removed because it does not make any sense. UpdateSourceTrigger determines the way the Binding source is updated, not the target. Read about DataBinding on MSDN to understand the terminology here.

  • The reason that using a String works and using a ComboBoxItem does not is because the default Type Converter for the Brush class (which is the type of the Window's Background) "understands" how to convert from a string, but not from a ComboBoxItem.

Comments