I've built a custom user control which inherits ComboBox and has items which are
KeyValuePair<bool, string>
I want to set the boolean default value of this ComboBox so that when true it shows "Yes" and when false it shows "No".
In the code below, when I set the selected value to true, then the ComboBox correctly shows "Yes".
But when I set the selected value to false, the ComboBox remains blank.
What do I need to do to this user control so that when I set the selected value to false, it shows "No"?
Window1.xaml:
<Window x:Class="TestYesNoComboBox234.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestYesNoComboBox234"
Title="Window1" Height="300" Width="300">
<StackPanel HorizontalAlignment="Left" Margin="10">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Contract available?" Margin="0 0 10 0"/>
<local:YesNoComboBox Width="60" Height="22"
x:Name="ContractAvailable"/>
</StackPanel>
</StackPanel>
</Window>
Window1.xaml.cs:
using System.Windows;
namespace TestYesNoComboBox234
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
//ContractAvailable.SelectedValue = true; //correctly sets "Yes"
ContractAvailable.SelectedValue = false; //incorrectly does not select anything
}
}
}
YesNoComboBox.xaml:
<ComboBox x:Class="TestYesNoComboBox234.YesNoComboBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
YesNoComboBox.xaml.cs:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace TestYesNoComboBox234
{
public partial class YesNoComboBox : ComboBox
{
public YesNoComboBox()
{
InitializeComponent();
Loaded += new RoutedEventHandler(YesNoComboBox_Loaded);
}
void YesNoComboBox_Loaded(object sender, RoutedEventArgs e)
{
SelectedValuePath = "Key";
Items.Add(new KeyValuePair<bool, string>(true, "Yes"));
Items.Add(new KeyValuePair<bool, string>(false, "No"));
}
}
}