将ComboBox SelectedValue绑定到字符串会禁用默认的SelectedValue wpf

时间:2015-06-08 13:50:37

标签: c# wpf binding combobox selectedvalue

我试图将ComboBox SelectedValue绑定到stringBinding完美无缺。但是,我的ComboBoxItem's 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

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

尝试使用string <{p>} 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>

MainWindow(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));
        }
    }
}

答案 1 :(得分:0)

您可以使用SelectedIndex强制控件预先选择一个值。

<ComboBox SelectedIndex="1" ... />

答案 2 :(得分:0)

如果删除SelectedValue属性,您的代码将起作用。 然后你需要的地方可以做这样的事情:

var item = (ComboBoxItem)SearchOptions.SelectedItem;
string text = item.Content;