WPF ComboBox 绑定到非字符串对象

发布于 2024-09-04 10:44:40 字数 5957 浏览 1 评论 0原文

我正在使用 MVVM (MVVM Light Toolkit),并且视图模型上有一个属性,它公开了对象列表。这些对象包含两个属性,都是字符串,与缩写和描述相关。我希望组合框将配对公开为“缩写 - 描述”。如果我使用数据模板,就可以轻松完成此操作。

我在视图模型上有另一个属性,它表示应显示为选定的对象 - 组合框中选定的项目。我将 ItemsSource 绑定到列表,因为它代表可用选择的范围,并尝试将 SelectedItem 绑定到该对象。我正在自杀,试图找出为什么我无法让它发挥作用,并且每小时都感觉自己更像是一个骗子。

在尝试了解其原理时,我创建了相同的方法,仅使用字符串列表和选定的字符串。这非常有效。所以,它显然与打字有关……也许与选择平等有关?或者可能与数据模板有关?

这是 XAML:

<Window x:Class="MvvmLight1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="300"
        Width="300"
        DataContext="{Binding Main, Source={StaticResource Locator}}">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <DataTemplate x:Key="DataTemplate1">
                <StackPanel Orientation="Horizontal">
                    <TextBlock TextWrapping="Wrap" Text="{Binding CourtCode}"/>
                    <TextBlock TextWrapping="Wrap" Text=" - "/>
                    <TextBlock TextWrapping="Wrap" Text="{Binding CourtDescription}"/>
                </StackPanel>
            </DataTemplate>
        </ResourceDictionary>
    </Window.Resources>

    <Grid x:Name="LayoutRoot">
        <ComboBox x:Name="cmbAbbrevDescriptions" Height="35" Margin="25,75,25,25"  VerticalAlignment="Top" ItemsSource="{Binding Codes}" ItemTemplate="{DynamicResource DataTemplate1}" SelectedItem="{Binding selectedCode}" />
        <ComboBox x:Name="cmbStrings" Height="35" Margin="25" VerticalAlignment="Top" ItemsSource="{Binding strs}" SelectedItem="{Binding selectedStr}"/>
    </Grid>
</Window>

如果有帮助的话,这是 ViewModel:

using GalaSoft.MvvmLight;
using MvvmLight1.Model;
using System.Collections.Generic;

namespace MvvmLight1.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        public const string CodesPropertyName = "Codes";
        private List<Court> _codes = null;
        public List<Court> Codes
        {
            get
            {
                return _codes;
            }

            set
            {
                if (_codes == value)
                {
                    return;
                }

                var oldValue = _codes;
                _codes = value;

                // Update bindings and broadcast change using GalaSoft.Utility.Messenging
                RaisePropertyChanged(CodesPropertyName, oldValue, value, true);
            }
        }

        public const string selectedCodePropertyName = "selectedCode";
        private Court _selectedCode = null;
        public Court selectedCode
        {
            get
            {
                return _selectedCode;
            }

            set
            {
                if (_selectedCode == value)
                {
                    return;
                }

                var oldValue = _selectedCode;
                _selectedCode = value;

                // Update bindings and broadcast change using GalaSoft.Utility.Messenging
                RaisePropertyChanged(selectedCodePropertyName, oldValue, value, true);
            }
        }

        public const string strsPropertyName = "strs";
        private List<string> _strs = null;
        public List<string> strs
        {
            get
            {
                return _strs;
            }

            set
            {
                if (_strs == value)
                {
                    return;
                }

                var oldValue = _strs;
                _strs = value;

                // Update bindings and broadcast change using GalaSoft.Utility.Messenging
                RaisePropertyChanged(strsPropertyName, oldValue, value, true);
            }
        }

        public const string selectedStrPropertyName = "selectedStr";
        private string _selectedStr = "";
        public string selectedStr
        {
            get
            {
                return _selectedStr;
            }

            set
            {
                if (_selectedStr == value)
                {
                    return;
                }

                var oldValue = _selectedStr;
                _selectedStr = value;

                // Update bindings and broadcast change using GalaSoft.Utility.Messenging
                RaisePropertyChanged(selectedStrPropertyName, oldValue, value, true);
            }
        }


        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            Codes = new List<Court>();

            Court code1 = new Court();
            code1.CourtCode = "ABC";
            code1.CourtDescription = "A Court";

            Court code2 = new Court();
            code2.CourtCode = "DEF";
            code2.CourtDescription = "Second Court";

            Codes.Add(code1);
            Codes.Add(code2);


            Court code3 = new Court();
            code3.CourtCode = "DEF";
            code3.CourtDescription = "Second Court";
            selectedCode = code3;

            selectedStr = "Hello";
            strs = new List<string>();
            strs.Add("Goodbye");
            strs.Add("Hello");
            strs.Add("Ciao");

        }
    }
}

这是正在公开的极其琐碎的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvvmLight1.Model
{
    public class Court
    {
        public string CourtCode { get; set; }

        public string CourtDescription { get; set; }
    }
}

谢谢!

I'm using MVVM (MVVM Light Toolkit) and have a property on the view model which exposes a list of objects. The objects contain two properties, both strings, which correlate to an abbreviation and a description. I want the ComboBox to expose the pairing as "abbreviation - description". If I use a data template, it does this easily.

I have another property on the view model which represents the object that should display as selected -- the chosen item in the ComboBox. I'm binding the ItemsSource to the list, as it represents the universe of available selections, and am trying to bind the SelectedItem to this object. I'm killing myself trying to figure out why I can't get it to work, and feeling more like a fraud by the hour.

In trying to learn why this works, I created the same approach with just a list of strings, and a selected string. This works perfectly. So, it clearly has something to do with the typing... perhaps something in choosing equality? Or perhaps it has to do with the data template?

Here is the XAML:

<Window x:Class="MvvmLight1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="300"
        Width="300"
        DataContext="{Binding Main, Source={StaticResource Locator}}">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <DataTemplate x:Key="DataTemplate1">
                <StackPanel Orientation="Horizontal">
                    <TextBlock TextWrapping="Wrap" Text="{Binding CourtCode}"/>
                    <TextBlock TextWrapping="Wrap" Text=" - "/>
                    <TextBlock TextWrapping="Wrap" Text="{Binding CourtDescription}"/>
                </StackPanel>
            </DataTemplate>
        </ResourceDictionary>
    </Window.Resources>

    <Grid x:Name="LayoutRoot">
        <ComboBox x:Name="cmbAbbrevDescriptions" Height="35" Margin="25,75,25,25"  VerticalAlignment="Top" ItemsSource="{Binding Codes}" ItemTemplate="{DynamicResource DataTemplate1}" SelectedItem="{Binding selectedCode}" />
        <ComboBox x:Name="cmbStrings" Height="35" Margin="25" VerticalAlignment="Top" ItemsSource="{Binding strs}" SelectedItem="{Binding selectedStr}"/>
    </Grid>
</Window>

And, if helpful, here is the ViewModel:

using GalaSoft.MvvmLight;
using MvvmLight1.Model;
using System.Collections.Generic;

namespace MvvmLight1.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        public const string CodesPropertyName = "Codes";
        private List<Court> _codes = null;
        public List<Court> Codes
        {
            get
            {
                return _codes;
            }

            set
            {
                if (_codes == value)
                {
                    return;
                }

                var oldValue = _codes;
                _codes = value;

                // Update bindings and broadcast change using GalaSoft.Utility.Messenging
                RaisePropertyChanged(CodesPropertyName, oldValue, value, true);
            }
        }

        public const string selectedCodePropertyName = "selectedCode";
        private Court _selectedCode = null;
        public Court selectedCode
        {
            get
            {
                return _selectedCode;
            }

            set
            {
                if (_selectedCode == value)
                {
                    return;
                }

                var oldValue = _selectedCode;
                _selectedCode = value;

                // Update bindings and broadcast change using GalaSoft.Utility.Messenging
                RaisePropertyChanged(selectedCodePropertyName, oldValue, value, true);
            }
        }

        public const string strsPropertyName = "strs";
        private List<string> _strs = null;
        public List<string> strs
        {
            get
            {
                return _strs;
            }

            set
            {
                if (_strs == value)
                {
                    return;
                }

                var oldValue = _strs;
                _strs = value;

                // Update bindings and broadcast change using GalaSoft.Utility.Messenging
                RaisePropertyChanged(strsPropertyName, oldValue, value, true);
            }
        }

        public const string selectedStrPropertyName = "selectedStr";
        private string _selectedStr = "";
        public string selectedStr
        {
            get
            {
                return _selectedStr;
            }

            set
            {
                if (_selectedStr == value)
                {
                    return;
                }

                var oldValue = _selectedStr;
                _selectedStr = value;

                // Update bindings and broadcast change using GalaSoft.Utility.Messenging
                RaisePropertyChanged(selectedStrPropertyName, oldValue, value, true);
            }
        }


        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            Codes = new List<Court>();

            Court code1 = new Court();
            code1.CourtCode = "ABC";
            code1.CourtDescription = "A Court";

            Court code2 = new Court();
            code2.CourtCode = "DEF";
            code2.CourtDescription = "Second Court";

            Codes.Add(code1);
            Codes.Add(code2);


            Court code3 = new Court();
            code3.CourtCode = "DEF";
            code3.CourtDescription = "Second Court";
            selectedCode = code3;

            selectedStr = "Hello";
            strs = new List<string>();
            strs.Add("Goodbye");
            strs.Add("Hello");
            strs.Add("Ciao");

        }
    }
}

And here is the ridiculously trivial class that is being exposed:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvvmLight1.Model
{
    public class Court
    {
        public string CourtCode { get; set; }

        public string CourtDescription { get; set; }
    }
}

Thanks!

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

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

发布评论

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

评论(2

江挽川 2024-09-11 10:44:40

运行时不知道 code2 和 code3 应该相等。

请参阅 http://msdn.microsoft.com/en-我们/库/ms173147(VS.80).aspx

public override bool Equals(object o)
{
   var court = o as Court;
   if(court == null)
      return false;
   return CourtCode == court.CourtCode;
}

The runtime doesn't know that code2 and code3 should be equal.

see http://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx

public override bool Equals(object o)
{
   var court = o as Court;
   if(court == null)
      return false;
   return CourtCode == court.CourtCode;
}
心欲静而疯不止 2024-09-11 10:44:40

您的 SelectedCode Code3 不存在于代码集合中。添加它以便选择能够按预期工作。

您的 selectedStr 有效,因为它位于集合中。 [strs.Add("Hello");]

Your SelectedCode Code3 is not present in the Codes collection. Add it so that the selection would work as expected.

Your selectedStr works because it is in the collection. [strs.Add("Hello");]

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