gpt4 book ai didi

c# - 将 ComboBox SelectedValue 绑定(bind)到字符串会禁用默认的 SelectedValue wpf

转载 作者:行者123 更新时间:2023-11-30 16:54:19 32 4
gpt4 key购买 nike

我正在尝试将 ComboBox SelectedValue 绑定(bind)到 stringBinding 完美运行。但是,我的 ComboBoxItem 的 IsSelected 之一设置为 True,但由于某种原因,当我启动应用程序时,没有选择任何项目,SelectedValue 是空白的,我需要重新选择我想要的项目。

这是我的代码:

XAML:

<ComboBox x:Name="SearchOptions" 
FontFamily="Times New Roman"
Foreground="DarkRed"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Grid.Column="2" Margin="10,0,0,0" Height="20"
SelectedValue="{Binding SearchType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

<ComboBoxItem x:Name="Contact" Content="A" FontFamily="Times New Roman" Foreground="DarkRed" HorizontalContentAlignment="Center" IsSelected="True"/>
<ComboBoxItem x:Name="Paper" Content="B" FontFamily="Times New Roman" Foreground="DarkRed" HorizontalContentAlignment="Center"/>

</ComboBox>

ViewModel 代码隐藏:

private string m_serachType;
public string SearchType
{
get { return m_serachType; }
set
{
m_serachType = value;
OnPropertyChanged("SearchType");
}
}

我的 ViewModel 类实现了 INotifyPropertyChanged

有什么想法吗?

最佳答案

尝试使用 string 代替 ComboboxItem:

主窗口(XAML)

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Grid>
<ComboBox SelectedItem="{Binding SearchType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
<sys:String>A</sys:String>
<sys:String>B</sys:String>
</ComboBox>
</Grid>
</Window>

主窗口 (cs)

public MainWindow()
{
InitializeComponent();
this.DataContext = new MyViewModel() { SearchType = "A" };
}

MyViewModel

class MyViewModel : INotifyPropertyChanged
{

private string m_serachType;
public string SearchType
{
get { return m_serachType; }
set
{
m_serachType = value;
OnPropertyChanged("SearchType");
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}

关于c# - 将 ComboBox SelectedValue 绑定(bind)到字符串会禁用默认的 SelectedValue wpf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30710922/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com