Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用MVVM绑定组合框SelectedItem_C#_Wpf_Data Binding_Mvvm_Binding - Fatal编程技术网

C# 使用MVVM绑定组合框SelectedItem

C# 使用MVVM绑定组合框SelectedItem,c#,wpf,data-binding,mvvm,binding,C#,Wpf,Data Binding,Mvvm,Binding,我的组合框中的SelectedItem有问题 <ComboBox Name="cbxSalesPeriods" ItemsSource="{Binding SalesPeriods}" DisplayMemberPath="displayPeriod" SelectedItem="{Binding SelectedSalesPeriod}" SelectedValuePath="displayPeriod" I

我的组合框中的SelectedItem有问题

<ComboBox Name="cbxSalesPeriods"
        ItemsSource="{Binding SalesPeriods}"
        DisplayMemberPath="displayPeriod"
        SelectedItem="{Binding SelectedSalesPeriod}"
        SelectedValuePath="displayPeriod"
        IsSynchronizedWithCurrentItem="True"/>

编辑: 如果删除属性DisplayMemberPath,会发生以下情况:

您似乎在
组合框上设置了不必要的属性。您可以删除具有不同用途的
DisplayMemberPath
SelectedValuePath
属性。你可以看看这里的帖子,了解这些属性的解释。试试这个:

<ComboBox Name="cbxSalesPeriods"
    ItemsSource="{Binding SalesPeriods}"
    SelectedItem="{Binding SelectedSalesPeriod}"
    IsSynchronizedWithCurrentItem="True"/>
public class SalesPeriodV
{
    private int month, year;

    public int Year
    {
        get { return year; }
        set
        {
            if (year != value)
            {
                year = value;
                NotifyPropertyChanged("Year");
            }
        }
    }

    public int Month
    {
        get { return month; }
        set
        {
            if (month != value)
            {
                month = value;
                NotifyPropertyChanged("Month");
            }
        }
    }

    public override string ToString()
    {
        return String.Format("{0:D2}.{1}", Month, Year);
    }

    public virtual event PropertyChangedEventHandler PropertyChanged;
    protected virtual void NotifyPropertyChanged(params string[] propertyNames)
    {
        if (PropertyChanged != null)
        {
            foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
        }
    }
}
然后,我在视图模型中添加了两个属性:

private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
    get { return salesPeriods; }
    set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
    get { return selectedItem; }
    set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}
然后数据仅将这两个属性绑定到组合框

<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />

就这样。。。这就是一个完美工作示例所需的全部内容。您应该看到,项目的显示来自
ToString
方法,而没有
displayPeriod
属性。希望您能从这个代码示例中找出错误。


<!-- xaml code-->
    <Grid>
        <ComboBox Name="cmbData"    SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
        <Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
    </Grid>



        //student Class
        public class Student
        {
            public  int Id { set; get; }
            public string name { set; get; }
        }

        //set 2 properties in MainWindow.xaml.cs Class
        public ObservableCollection<Student> studentInfo { set; get; }
        public Student SelectedstudentInfo { set; get; }

        //MainWindow.xaml.cs Constructor
        public MainWindow()
        {
            InitializeComponent();
            bindCombo();
            this.DataContext = this;
            cmbData.ItemsSource = studentInfo;

        }

        //method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
        public void bindCombo()
        {
            ObservableCollection<Student> studentList = new ObservableCollection<Student>();
            studentList.Add(new Student { Id=0 ,name="==Select=="});
            studentList.Add(new Student { Id = 1, name = "zoyeb" });
            studentList.Add(new Student { Id = 2, name = "siddiq" });
            studentList.Add(new Student { Id = 3, name = "James" });

              studentInfo=studentList;

        }

        //button click to get selected student MainWindow.xaml.cs
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student student = SelectedstudentInfo;
            if(student.Id ==0)
            {
                MessageBox.Show("select name from dropdown");
            }
            else
            {
                MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
            }
        }
好啊 //学生班 公立班学生 { 公共int Id{set;get;} 公共字符串名称{set;get;} } //在MainWindow.xaml.cs类中设置2个属性 公共可观察集合学生信息{set;get;} 公立学生选择学生信息{set;get;} //MainWindow.xaml.cs构造函数 公共主窗口() { 初始化组件(); bindCombo(); this.DataContext=this; cmbData.ItemsSource=学生信息; } //方法绑定cobobox,或者您可以从MainWindow.xaml.cs中的数据库获取数据 公共void bindCombo() { ObservableCollection studentList=新的ObservableCollection(); 添加(新学生{Id=0,name=“==Select==”}); Add(新学生{Id=1,name=“zoyeb”}); Add(新学生{Id=2,name=“siddiq”}); Add(新学生{Id=3,name=“James”}); studentInfo=学生列表; } //按钮单击以获取所选的student MainWindow.xaml.cs 私有无效按钮\u单击(对象发送者,路由目标e) { 学生=已选择的学生信息; 如果(student.Id==0) { MessageBox.Show(“从下拉列表中选择名称”); } 其他的 { MessageBox.Show(“Name:+student.Name+”Id:+student.Id); } }
我遇到了一个类似的问题,当我在组合框中选择某个内容时,SelectedItem绑定没有更新。我的问题是,我必须为绑定设置UpdateSourceTrigger=PropertyChanged

<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />


但这并不能回答这个问题。设置这些属性不应在给定上下文中导致所描述的行为。我已尝试删除这些属性,但无效。我已经编辑了第一篇帖子。@NikitaBrizhak我承认我的原始答案没有为用户提供完整的解决方案。然而,在回答了很多这些问题后,我意识到,由于一些原因,例如缺乏信息或问题作者的理解,能够立即提供答案的情况非常罕见。因此,我养成了分阶段回答这些问题的习惯,你刚刚看到了第一个问题。现在你可以看到第二阶段。也许在将来,你可以给知名用户带来质疑的好处,并将这些类型的评论留给新用户?@Sheridan,我只是指出,虽然你的建议从代码审阅者的角度来看是有效的,但他们并不试图解决眼前的问题。这没有害处,是吗?很抱歉,如果我的评论听起来有冒犯之意,我不是那个意思。@Sheridan,“也许将来你可以让知名用户免于怀疑,并将这些类型的评论留给新用户?”->很有趣:-)你应该创建一个沙箱应用程序。只留下一个组合框,然后删除所有其他内容。那么你应该试着重现这个问题。你可能无法做到。然后比较这两个应用程序,看看哪种差异会导致这种行为。我怀疑您提供的代码中是否存在问题。还要注意,您的组合框有一个名称。查看代码隐藏文件,看看是否有一些与选择有关的代码。这一个是为我做的,谢谢
<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />
<!-- xaml code-->
    <Grid>
        <ComboBox Name="cmbData"    SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
        <Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
    </Grid>



        //student Class
        public class Student
        {
            public  int Id { set; get; }
            public string name { set; get; }
        }

        //set 2 properties in MainWindow.xaml.cs Class
        public ObservableCollection<Student> studentInfo { set; get; }
        public Student SelectedstudentInfo { set; get; }

        //MainWindow.xaml.cs Constructor
        public MainWindow()
        {
            InitializeComponent();
            bindCombo();
            this.DataContext = this;
            cmbData.ItemsSource = studentInfo;

        }

        //method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
        public void bindCombo()
        {
            ObservableCollection<Student> studentList = new ObservableCollection<Student>();
            studentList.Add(new Student { Id=0 ,name="==Select=="});
            studentList.Add(new Student { Id = 1, name = "zoyeb" });
            studentList.Add(new Student { Id = 2, name = "siddiq" });
            studentList.Add(new Student { Id = 3, name = "James" });

              studentInfo=studentList;

        }

        //button click to get selected student MainWindow.xaml.cs
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student student = SelectedstudentInfo;
            if(student.Id ==0)
            {
                MessageBox.Show("select name from dropdown");
            }
            else
            {
                MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
            }
        }
<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />