WPF绑定并填充组合框 [英] WPF Bind and populate a combobox

查看:66
本文介绍了WPF绑定并填充组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#和WPF的新手,我的问题可能对你们这些人来说太容易了:

我编写了一个类成员并设置其参数读取任何本地xml。其中一个参数是Int参数。我想要一个组合框来处理这个参数但是要显示一个字符串。我的方法是创建一个字典,填充组合并从类成员绑定其选定的值:

 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Windows;
使用 System.Windows.Controls;
使用 System.Windows.Data;
使用 System.Windows.Documents;
使用 System.Windows.Input;
使用 System.Windows.Media;
使用 System.Windows.Media.Imaging;
使用 System.Windows.Navigation;
使用 System.Windows.Shapes;
使用 System.ComponentModel;
使用 System.Xml;
使用 System.Xml.Linq;

命名空间 TempProject
{
class 字典
{
public static 字典< int,string> GetChoise()
{
Dictionary< int,string> MyDict = new Dictionary< int,string>();
MyDict.Add( 1 choise 1\" );
MyDict.Add( 2 choise 2\" );
MyDict.Add( 3 choise 3\" );
return MyDict;
}
}

public class MyModel: INotifyPropertyChanged
{
private int m_choise;

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged( string propertyName)
{
if (PropertyChanged!= null
{
PropertyChanged( this new PropertyChangedEventArgs(propertyName));
}
}

public int 选择
{
get { return m_choise; }
set
{
if value < 1 || > 3 ){ throw new OverflowException(); }
m_choise = value ; OnPropertyChanged( Choise);
}
}
}

public partial class MainWindow:Window
{
MyModel Model1 = new MyModel( );
public MainWindow()
{
this .InitializeComponent() ;
DataContext = Model1;
}

private void CmdOpenXML( object sender,System.Windows.RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.InitialDirectory = @ C:\;
dlg.DefaultExt = 。xml;
dlg.Filter = XML | * .xml;
Nullable< bool> result = dlg.ShowDialog();
if (result == true
{
XDocument xd = XDocument.Load(dlg.FileName);
var query = 来自 d xd.Root.Descendants( PROJECT
选择 d;
foreach var q in 查询)
{Model1.Choise = Int32 .Parse(q.Element( < span class =code-string> choise
)。Value); }
}
}
}
}





和XAML:

 <  窗口    x:Class   =  TempProject.MainWindow  

xmlns = http ://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x = http://schemas.microsoft.com/winfx/2006/xaml

< span class =code-attribute> xmlns:local = clr-namespace:TempProject

标题 = MainWindow 高度 = 350 宽度 = < span class =code-keyword> 525 >
< Window.Resources >
< ObjectDataProvider x:键 = MyDict

ObjectType = {x:输入local:Dictionaries}

< span class =code-attribute> MethodName = GetChoise / < span class =code-keyword>>
< / Window.Resources >
< StackPanel >
< 菜单 > ;
< MenuItem 标题 = 文件 >
< MenuItem 标题 = 打开 点击 = CmdOpenXML / >
< / MenuItem >
< /菜单 >
< TextBox 文字 = {Binding Choise} / >
< ComboBox ItemsSource = {Binding Source = {StaticResource MyDict}}

SelectedValuePath = Key

DisplayMemberPath =

SelectedItem = {Binding Path = Choise ,Mode = TwoWay} / >
< / StackPanel >
< / Window >





但是组合不能正常工作。

你能告诉我我做错了什么吗?一般来说我的方法是否正确?

你能建议我一些关于这个主题的教程吗?

谢谢

解决方案

< blockquote>毕竟很简单。应该在ComboBox中使用SelectedValue而不是SelectedItem


I''m new to C# and WPF and my question may be too easy to some of you:
My prog crates a class member and sets its parameters reading any local xml. One of the parameters is an Int parameter. I want a combobox to handle this parameter but to show a string. My approach is to create a dictionary witch populates the combo and bind its selected value from the class member:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Xml;
using System.Xml.Linq;

namespace TempProject
{
    class Dictionaries
    {
        public static Dictionary<int, string> GetChoise()
        {
            Dictionary<int, string> MyDict = new Dictionary<int, string>();
            MyDict.Add(1, "choise 1");
            MyDict.Add(2, "choise 2");
            MyDict.Add(3, "choise 3");
            return MyDict;
        }
    }

    public class MyModel : INotifyPropertyChanged
    {
        private int m_choise;

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public int Choise
        {
            get { return m_choise; }
            set
            {
                if (value < 1 || value > 3) { throw new OverflowException(); }
                m_choise = value; OnPropertyChanged("Choise");
            }
        }
    }

    public partial class MainWindow : Window
    {
        MyModel Model1 = new MyModel();
        public MainWindow()
        {
            this.InitializeComponent();
            DataContext = Model1;
        }

        private void CmdOpenXML(object sender, System.Windows.RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.InitialDirectory = @"C:\";
            dlg.DefaultExt = ".xml";
            dlg.Filter = "XML|*.xml";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                XDocument xd = XDocument.Load(dlg.FileName);
                var query = from d in xd.Root.Descendants("PROJECT")
                            select d;
                foreach (var q in query)
                { Model1.Choise = Int32.Parse(q.Element("choise").Value); }
            }
        }
    }
}



and the XAML:

<Window x:Class="TempProject.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:local="clr-namespace:TempProject"

        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ObjectDataProvider x:Key="MyDict"

                            ObjectType="{x:Type local:Dictionaries}"

                            MethodName="GetChoise"/>
    </Window.Resources>
    <StackPanel >
            <Menu>
                <MenuItem Header="File">
                    <MenuItem Header="Open" Click="CmdOpenXML" />
                </MenuItem>
            </Menu>
            <TextBox Text="{Binding Choise}" />
            <ComboBox ItemsSource="{Binding Source={StaticResource MyDict}}" 

                      SelectedValuePath="Key" 

                      DisplayMemberPath="Value" 

                      SelectedItem="{Binding Path=Choise,Mode=TwoWay}"/>
    </StackPanel>
</Window>



But the combo does not work correctly.
Can you tell me what am I doing wrong? Is my approach correct in general?
Can you suggest me some tutorials on the subject?
Thank you

解决方案

It was simple after all. Should have used SelectedValue instead of SelectedItem in ComboBox


这篇关于WPF绑定并填充组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆