您可以將所選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
只是出於好奇,爲什麼你需要通過標籤選擇項目?你能解釋一下用例嗎? –