您可以将所选COMBOX值绑定到一个依赖属性。例如,这里是一个依赖属性“CurrentTag”一个窗口:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
CurrentTag = "4";
}
public static readonly DependencyProperty CurrentTagProperty = DependencyProperty.Register(
"CurrentTag", typeof(string), typeof(Window1),
new PropertyMetadata("1"));
public string CurrentTag
{
get { return (string)this.GetValue(CurrentTagProperty); }
set { this.SetValue(CurrentTagProperty, value); }
}
}
,并在XAML:
<Window x:Class="WpfComboboxBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="100" Width="300"
x:Name="window1">
<StackPanel VerticalAlignment="Center">
<ComboBox Name="myMenu"
SelectedValue="{Binding ElementName=window1, Path=CurrentTag, Mode=TwoWay}"
SelectedValuePath="Tag">
<ComboBoxItem Content="Question 1" Tag="1" />
<ComboBoxItem Content="Question 2" Tag="2" />
<ComboBoxItem Content="Question 3" Tag="3" />
<ComboBoxItem Content="Question 4" Tag="4" />
</ComboBox>
</StackPanel>
</Window>
然后改变所选择的项目,你只需修改属性的值,如在上面的例子中(CurrentTag =“4”;)
来源
2011-10-06 14:00:51
Jem
只是出于好奇,为什么你需要通过标签选择项目?你能解释一下用例吗? –