【发布时间】:2010-12-02 08:35:32
【问题描述】:
我已经构建了一个 自定义用户控件,它继承了 ComboBox 并具有
KeyValuePair<bool, string>
我想设置这个 ComboBox 的 boolean 默认值,这样当 true 时它显示“Yes”,当它为 false 时显示“ 否”。
在下面的代码中,当我将选定的值设置为 true 时,ComboBox 正确显示“是”。
但是当我将选定的值设置为 false 时,ComboBox 仍为空白。
我需要对此用户控件执行什么操作,以便当我将所选值设置为 false 时,它会显示“否”?
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"));
}
}
}
【问题讨论】: