在WPF中选择静态ComboBoxItems中的Item
本文关键字:ComboBoxItems 中的 Item 静态 选择 WPF | 更新日期: 2023-09-27 18:09:57
我有一个带有静态项的ComboBox
<ComboBox SelectedItem="{Binding SelectedOperator}" >
<ComboBoxItem Content="=" IsSelected="True" />
<ComboBoxItem Content=">" />
<ComboBoxItem Content="<" />
</ComboBox>
,但是第一项没有被选中,尽管设置了IsSelected="True"
。
我可以在WPF中选择它吗?如果真的有必要,我只想在代码后面做。
您可能想要使用ComboBoxItem的Content
字符串为SelectedOperator
绑定,在这种情况下,您可以使用FallbackValue
:
<ComboBox SelectedValuePath="Content"
SelectedValue="{Binding SelectedOperator, FallbackValue='=}">
<ComboBoxItem Content="=" />
<ComboBoxItem Content=">" />
<ComboBoxItem Content="<" />
</ComboBox>
如果您必须将所有内容保持在XAML中,则可以将ComboBox命名并从其他元素绑定到其SelectedItem。您不会绑定到SelectedOperator以便在VM/codebehind中使用,但这可能不是一个交易破坏者,这取决于您的应用程序如何设置。
<Grid x:Name="LayoutRoot" HorizontalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ComboBox x:Name="MyComboBox"
Grid.Row="0"
Width="80"
Height="25">
<ComboBoxItem Content="=" IsSelected="True" />
<ComboBoxItem Content=">" />
<ComboBoxItem Content="<" />
</ComboBox>
<TextBox Grid.Row="1" Text="{Binding ElementName=MyComboBox, Path=SelectedItem.Content}" />
</Grid>
你的ComboBox
会怎么选择是SelectedItem
?
您将SelectedItem
设置为"{Binding SelectedOperator}"
,同时尝试将第一项的IsSelected
属性设置为True
。
任意设置SelectedItemBinding
<ComboBox SelectedItem="{Binding SelectedOperator}" >
<ComboBoxItem Content="=" />
<ComboBoxItem Content=">" />
<ComboBoxItem Content="<" />
</ComboBox>
或set IsSelected
property:
<ComboBox>
<ComboBoxItem Content="=" IsSelected="True" />
<ComboBoxItem Content=">" />
<ComboBoxItem Content="<" />
</ComboBox>
希望这对你有帮助。
<ComboBox Margin="53,119,35,157"
SelectedValue="{Binding SelectedOperator}"
SelectedValuePath="Content">
<ComboBoxItem Content="=" />
<ComboBoxItem Content=">" />
<ComboBoxItem Content="<" />
</ComboBox>
背后的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var v = new ViewModel();
this.DataContext = v;
}
}
ViewModel:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
SelectedOperator = "=";
}
private string _selectedOperator;
public string SelectedOperator
{
get { return _selectedOperator; }
set { _selectedOperator = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}