在 WPF 中以编程方式设置 ComboBox SelectedItem (3.5sp1)

发布于 2024-08-21 01:21:54 字数 1004 浏览 7 评论 0原文

在安装了 Net Framework 3.5 sp1 的 wpf 应用程序中以编程方式设置 SelectedItem 时,我感到很困惑。我仔细阅读了数百篇文章\主题,但仍然感到困惑(( 我的 xaml:

 <ComboBox name="cbTheme">
    <ComboBoxItem>Sunrise theme</ComboBoxItem>
    <ComboBoxItem>Sunset theme</ComboBoxItem> 
 </ComboBox>

如果我在其中一项中添加 IsSelected="True" 属性 - 它不会设置该项目被选中。为什么 ? 我在代码中尝试了不同的方法,但仍然无法设置所选项目:

cbTheme.SelectedItem=cbTheme.Items.GetItemAt(1); //dosn't work
cbTheme.Text = "Sunrise theme"; //dosn't work
cbTheme.Text = cbTheme.Items.GetItemAt(1).ToString();//dosn't work
cbTheme.SelectedValue = ...//dosn't work
cbTheme.SelectedValuePath = .. //dosn't work
//and even this dosn't work:
ComboBoxItem selcbi = (ComboBoxItem)cbTheme.Items.GetItemAt(1);//or selcbi = new ComboBoxItem
cbTheme.SelectedItem = selcbi;

SelectedItem 不是只读属性,那么为什么它不起作用? 我认为这应该是微软的问题,而不是我的问题。还是我错过了什么???我尝试使用 ListBox,并且使用相同的代码都可以正常工作,我可以设置选择、获取选择等等......那么我可以用 ComboBox 做什么?也许有一些技巧?

I have been confused while setting SelectedItem programmaticaly in wpf applications with Net Framework 3.5 sp1 installed. I have carefully read about hundred posts \topics but still confused((
My xaml:

 <ComboBox name="cbTheme">
    <ComboBoxItem>Sunrise theme</ComboBoxItem>
    <ComboBoxItem>Sunset theme</ComboBoxItem> 
 </ComboBox>

If I add IsSelected="True" property in one of the items - it's dosn't sets this item selected. WHY ?
And i was try different in code and still can't set selected item:

cbTheme.SelectedItem=cbTheme.Items.GetItemAt(1); //dosn't work
cbTheme.Text = "Sunrise theme"; //dosn't work
cbTheme.Text = cbTheme.Items.GetItemAt(1).ToString();//dosn't work
cbTheme.SelectedValue = ...//dosn't work
cbTheme.SelectedValuePath = .. //dosn't work
//and even this dosn't work:
ComboBoxItem selcbi = (ComboBoxItem)cbTheme.Items.GetItemAt(1);//or selcbi = new ComboBoxItem
cbTheme.SelectedItem = selcbi;

The SelectedItem is not readonly property, so why it wan't work?
I think thats should be a Microsoft's problems, not my. Or I have missed something??? I have try playing with ListBox, and all work fine with same code, I can set selections, get selections and so on.... So what can I do with ComboBox ? Maybe some tricks ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

你另情深 2024-08-28 01:21:54

要选择 ComboBox 中的任何项目并将其设置为默认选择的项目,只需使用以下行:

combobox.SelectedIndex = 0; //index should be the index of item which you want to be selected

To select any item in the ComboBox and to set it as default item selected just use the below line:

combobox.SelectedIndex = 0; //index should be the index of item which you want to be selected
哀由 2024-08-28 01:21:54

如果我以编程方式添加组合框和项目,这对我有用:

ComboBox newCombo = new ComboBox();

ComboBoxItem newitem = new ComboBoxItem();
newitem.Content = "test 1";
newCombo.Items.Add(newitem);
newitem = new ComboBoxItem();
newitem.Content = "test 2";
newCombo.Items.Add(newitem);
newitem = new ComboBoxItem();
newitem.Content = "test 3";
newCombo.Items.Add(newitem);

newCombo.SelectedItem =  ((ComboBoxItem)newCombo.Items[1]);
newCombo.Text = ((ComboBoxItem)newCombo.Items[1]).Content.ToString();

newStack.Children.Add(newCombo);

如果以编程方式设置 ItemSource 属性,然后将文本设置为所选值,它也有效。

If i add the combobox and items programmatically, this works for me:

ComboBox newCombo = new ComboBox();

ComboBoxItem newitem = new ComboBoxItem();
newitem.Content = "test 1";
newCombo.Items.Add(newitem);
newitem = new ComboBoxItem();
newitem.Content = "test 2";
newCombo.Items.Add(newitem);
newitem = new ComboBoxItem();
newitem.Content = "test 3";
newCombo.Items.Add(newitem);

newCombo.SelectedItem =  ((ComboBoxItem)newCombo.Items[1]);
newCombo.Text = ((ComboBoxItem)newCombo.Items[1]).Content.ToString();

newStack.Children.Add(newCombo);

It also works if it set the ItemSource property programmatically, then set the text to the selected value.

好倦 2024-08-28 01:21:54

在视图模型中为主题列表创建一个公共属性,并为所选项目创建一个公共属性:

    private IEnumerable<string> _themeList;
    public IEnumerable<string> ThemeList
    {
        get { return _themeList; }
        set
        {
            _themeList = value;
            PropertyChangedEvent.Notify(this, "ThemeList");
        }
    }
    private string _selectedItem;
    public string SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            PropertyChangedEvent.Notify(this,"SelectedItem");
        }            
    }

将 xaml 中的组合框绑定到属性,如下所示:

    <ComboBox 
        Name="cbTheme" 
        ItemsSource="{Binding ThemeList}"      
        SelectedItem="{Binding SelectedItem}">
    </ComboBox>

现在您要做的就是将项目添加到 ThemeList 以填充组合框。要选择列表中的项目,请将 selected 属性设置为您想要选择的项目的文本,如下所示:

    var tmpList = new List<string>();
    tmpList.Add("Sunrise theme");
    tmpList.Add("Sunset theme");

    _viewModel.ThemeList = tmpList;
    _viewModel.SelectedItem = "Sunset theme";

或者尝试将 selected 项目设置为您想要在自己的代码中选择的项目的字符串值(如果您想使用您当前拥有的代码 - 不确定它是否有效,但您可以尝试。

Create a public property in your viewmodel for the theme list and one for the selected item:

    private IEnumerable<string> _themeList;
    public IEnumerable<string> ThemeList
    {
        get { return _themeList; }
        set
        {
            _themeList = value;
            PropertyChangedEvent.Notify(this, "ThemeList");
        }
    }
    private string _selectedItem;
    public string SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            PropertyChangedEvent.Notify(this,"SelectedItem");
        }            
    }

bind your combobox in xaml to the properties like this:

    <ComboBox 
        Name="cbTheme" 
        ItemsSource="{Binding ThemeList}"      
        SelectedItem="{Binding SelectedItem}">
    </ComboBox>

now all you do is add items to the ThemeList to populate the combobox. To select an item in the list, set the selected property to the text of the item you want selected like this:

    var tmpList = new List<string>();
    tmpList.Add("Sunrise theme");
    tmpList.Add("Sunset theme");

    _viewModel.ThemeList = tmpList;
    _viewModel.SelectedItem = "Sunset theme";

or try setting the selected item to the string value of the item you want selected in your own code if you want to use the code you currently have - not sure if it will work but you can try.

人│生佛魔见 2024-08-28 01:21:54

如果您知道要设置的项目的索引,在这种情况下,看起来您正在尝试设置索引 1,您只需这样做:

cbTheme.SelectedIndex = 1;

我发现当您不知道索引时,那才是真正的问题所在。我知道这超出了最初的问题,但对于那些想知道如何在索引未知但要显示的值已知时设置项目的 Google 员工来说,如果您用 < 填充下拉列表, 获取该索引:

int matchedIndex = 0;
if (dt != null & dt.Rows != null)
{
    if (dt.Rows.Count > 0)
    {
        foreach (DataRow dr in dt.Rows)
        {
            string myRowValue = dr["SOME_COLUMN"] != null ? dr["SOME_COLUMN"].ToString() : String.Empty;
            if (myRowValue == "Value I Want To Set")
                break;
            else
                matchedIndex++;
        }
     }
 }

例如,从 DataTable

如果 ComboBox 按 OP 显示的方式填充,则对 ComboBoxItem 项而不是 DataRow 行进行类似的迭代可能会产生类似的结果。

If you know the index of the item you want to set, in this case it looks like you are trying to set index 1, you simply do:

cbTheme.SelectedIndex = 1;

I found that when you don't know the index, that's when you have the real issue. I know this goes beyond the original question, but for Googlers on that count that want to know how to set the item when the index isn't known but the value you want to display IS known, if you are filling your dropdown with an ItemSource from a DataTable, for example, you can get that index by doing this:

int matchedIndex = 0;
if (dt != null & dt.Rows != null)
{
    if (dt.Rows.Count > 0)
    {
        foreach (DataRow dr in dt.Rows)
        {
            string myRowValue = dr["SOME_COLUMN"] != null ? dr["SOME_COLUMN"].ToString() : String.Empty;
            if (myRowValue == "Value I Want To Set")
                break;
            else
                matchedIndex++;
        }
     }
 }

And then you do simply do cbTheme.SelectedIndex = matchedIndex;.

A similar iteration of ComboBoxItem items instead of DataRow rows could yield a similar result, if the ComboBox was filled how the OP shows, instead.

莳間冲淡了誓言ζ 2024-08-28 01:21:54

ComboBox 是否绑定数据?

如果是这样,您可能最好通过绑定而不是代码来完成......

请参阅这个问题... WPF ListView 以编程方式选择项目

也许创建一个新的 SelectableObject {Text = "Abc Theme", IsCurrentlySelected = True}
将 SelectableObject 的集合绑定到 ComboBox。

本质上是在模型中设置 IsCurrentlySelected 属性并从模型更新 UI。

Is the ComboBox data bound?

If so you are probably better to do it through Binding rather than code ....

See this question ... WPF ListView Programmatically Select Item

Maybe create a new SelectableObject {Text = "Abc Theme", IsCurrentlySelected = True}
Bind a collection of SelectableObjects to the ComboBox.

Essentially setting the IsCurrentlySelected property in the model and having UI update from the Model.

开始看清了 2024-08-28 01:21:54

根据答案 4

如果您已经在项目源中添加了项目。
触发 selectet Value 的 PropertyChangedEvent。

tmpList.Add("Sunrise theme"); 
    tmpList.Add("Sunset theme");
    PropertyChangedEvent.Notify(this,"SelectedItem");

Acording Answer 4

If you already add the Items in the Item source.
Fire the PropertyChangedEvent of the selectet Value.

tmpList.Add("Sunrise theme"); 
    tmpList.Add("Sunset theme");
    PropertyChangedEvent.Notify(this,"SelectedItem");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文