WPF绑定COMBOX不同的目录,不同的SelectedValue [英] WPF Binding Combox with different List and different SelectedValue

查看:217
本文介绍了WPF绑定COMBOX不同的目录,不同的SelectedValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的用户ucStep2我有Step2InfoData对象的DataContext与沿有几个属性:

In my UserControl ucStep2 I have DataContext of Step2InfoData object that has several properties along with :

    private string rockDensUnit;
    public string RockDensity_Unit {
        get { return rockDensUnit; }
        set
        {
            if (rockDensUnit != value)
            {
                rockDensUnit = value;
                Changed("RockDensity_Unit");
            }
        }
    }

在我的应用我有绑定几个组合的不同,通常的测量类型,如{千克/立方米,克/立方米},{米,厘米}等措施,这类群体。我的意思是,多组合的同一项目有名单。所以我$ pferred创建这样的列表,我可以在多个组合使用的类是P&$。我创建了包含所有项目ComboItems.cs列出了我将需要填充下拉。

In my app I got to bind several combo's with different normally measurement types Like {kg/m3, gm/m3}, {meter, cm} and so on such groups of measures. I mean, multiple combo's to have list of same items. So I preferred to create Class's of such lists that I can use in multiple combos. I created ComboItems.cs which contains all items lists that I will need to populate the drop down.

ComboItems.cs

ComboItems.cs

 **OBJECTS I USE FOR LIST OF IEMS** 
// Class for kg, gm
public class KgGmItems
{
    public ObservableCollection<string> KgGmList { get; set; }

    public KgGmItems()
    {
        KgGmList = new ObservableCollection<string>();
        KgGmList.Add("kg/m3");
        KgGmList.Add("gram/cm3");
    }

    public string ValueSelected { get; set; }  // Don't know if this is useful in my case
}

// Class for meter, cm
public class MtCmItems : INotifyPropertyChanged
{
    public MtCmItems()
    {
        Dict = new Dictionary<string, string>
        {
            {"meter", "meter"}, 
            {"centimeter", "centimeter"}
        };
    }
    ....................
 }

XML即ucStep2查看

XML i.e. ucStep2 View

<!-- As the objects KgGmItems doesn't contain in ucStep2.xaml.cs or Step2InfoData (that is bound to this UC) so add reference of those classes -->
<UserControl.Resources>
    <ObjectDataProvider x:Key="KgGmObj" ObjectType="{x:Type top:KgGmItems}" />
    <ObjectDataProvider x:Key="MtCmObj" ObjectType="{x:Type top:MtCmItems}" />
</UserControl.Resources>

  <ComboBox DataContext="{StaticResource KgGmObj}" ItemsSource="{Binding KgGmList}"  SelectedValue="{Binding Path=RockDensity_Unit, Mode=TwoWay}" SelectedIndex="0" 
   Background="#FFB7B39D" Grid.Row="5" Height="23" HorizontalAlignment="Left" Margin="401,61,0,0" Name="comboBox6" VerticalAlignment="Top" Width="84" Visibility="Hidden">
  </ComboBox>

我要显示从KgGmItems类ObservableCllection KgGmList项目和所选的值绑定到类Step2InfoData的RockDensity_Unit绑定到该用户控件。

I want to display ObservableCllection KgGmList items from KgGmItems class and bind the selected value to RockDensity_Unit of class Step2InfoData that is bound to this UserControl.

在上面的组合,我能够显示在下拉菜单中的所有项目下来,还第一个项目是默认选择。但价值不绑定到RockDensity_Unit;它的值保持为空。

In the above combo, I am able to display all items in the drop down, also 1st item is selected by default. But the value is not bind to RockDensity_Unit; it's value remains null.

我要2路时RockDensity_Unit proeprtiy的值设置编程即值应在下拉选择下降这种情况发生。当然该值应该存在于列表中。

I want this to happen 2-way i.e. when RockDensity_Unit proeprtiy's value is set programmatically, the value should be selected in the drop down. Of course the value should exists in the list.

默认情况下,第一个项目应该被选中。

By default the 1st item should be selected.

更新
新增的DependencyProperty在ucStep2.xaml.cs

UPDATE Added DependencyProperty in ucStep2.xaml.cs

 public static readonly DependencyProperty RockDensityUnitProperty =
   DependencyProperty.Register("RockDensity_Unit", typeof(string), typeof(UserControl),
   new FrameworkPropertyMetadata("kg/m3", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));  

public string RockDensity_Unit
{
        get { return this.GetValue(RockDensityUnitProperty) as string; }
        set { SetValue(RockDensityUnitProperty, value); }
}

XML

<ComboBox DataContext="{StaticResource KgGmObj}" ItemsSource="{Binding KgGmList}"  SelectedItem="{Binding Path=RockDensity_Unit, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ucStep2}}, Mode=TwoWay}" 
   Background="#FFB7B39D" Grid.Row="5" Height="23" HorizontalAlignment="Left" Margin="401,61,0,0" Name="comboBox6" VerticalAlignment="Top" Width="84" Visibility="Hidden">
</ComboBox>

错误
      错误1类型引用无法找到名为'ucStep2公共类型。线74的位置194结果
这是指组合框,FindAncestor后

ERROR Error 1 The type reference cannot find a public type named 'ucStep2'. Line 74 Position 194.
This refers to the combobox ", " after FindAncestor

析疑
在Step2InfoData的RockDensity_Unit CLR属性是不变。

DOUBT The RockDensity_Unit CLR property in Step2InfoData is untouched.

为什么code无法找到ucStep2?仅供参考,我想这可能是你的任何参考文献:

Why is the code not able to find ucStep2 ? FYI, I think this may be of any reference for you :

<UserControl x:Class="WellBore.ucStep2"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:WellBore.Models"
         xmlns:top="clr-namespace:WellBore"
         mc:Ignorable="d" 
         d:DesignHeight="870" d:DesignWidth="700" MaxHeight="970" MinHeight="700" MaxWidth="600">

任何帮助是非常AP preciated。

Any help is highly appreciated.

感谢

推荐答案

好吧,让我们得到这个工作的结合......首先,我使用从 KgGmItems 类绑定到组合框。在这个类有字符串值的集合中的下降,显示下降和字符串属性绑定到 ComboBox.SelectedItem ...完美!现在,我假设你有这个类中的资源实例部分名为 KgGmObj ...让我们继续简单入手:

Ok, so let's get this binding working... first, I am using an item from your KgGmItems class to bind to the ComboBox. In this class you have a collection of string values to display in the drop down and a string property to bind to the ComboBox.SelectedItem... perfect! Now I'm assuming that you have an instance of this class in the Resources section called KgGmObj... let's keep it simple to start with:

<ComboBox DataContext="{StaticResource KgGmObj}" ItemsSource="{Binding KgGmList}" 
SelectedItem="{Binding ValueSelected, Mode=TwoWay}" />

这是所有你需要设置组合框和类之间的绑定。但有一件事要注意的是,当您试图选择的项目从code设置,它会的只有的,如果你把它设置为集合在实际项目中的一个工作...我觉得用字符串 S当这并不真正指望,但无论如何,要知道这是很重要的。如果你设置一个自定义类如组合框对象的类型来代替,那么你可以设置所选择的项目是这样的:

This is all you need to setup the binding between the ComboBox and your class. One thing to note though, is that when you try to set the selected item from your code, it will only work if you set it to one of the actual items in the collection... I think that this doesn't really count when using strings, but it's important to know this anyway. If you were setting a custom class as the type of objects in the ComboBox instead, then you could set the selected item like this:

ValueSelected = KgGmList.Where(item => item.Name == "NameOfObjectToMatch").Single();

或更好,这样,如果你有一个唯一识别的属性:

Or better like this if you had a uniquely identifiable property:

ValueSelected = KgGmList.Where(item => item.Id == Id).Single()

通过您的字符串的价值观,你的的可以设置从code所选择的项目是这样的:

With your string values, you should be able to set the selected item from code like this:

ValueSelected = "Some value";

更新>>>好了,让我们有另一个去......我的认为的我的可能的有足够的信息,现在去。我认为,你想要的东西是这样的:

UPDATE >>> Ok, so let's have another go... I think that I may have enough information to go on now. I think that you want something like this:

<ComboBox DataContext="{StaticResource KgGmObj}" ItemsSource="{Binding KgGmList}" 
SelectedItem="{Binding RockDensity_Unit, Mode=TwoWay}" />

这里的问题是,你已经设置的的DataContext 组合框你的 KgGmObj 对象。这意味着该框架是要设法找到该对象命名的属性 RockDensity_Unit 的。我也看到你的这个属性的定义,另一个潜在的问题。

The problem with this is that you have set the DataContext of the ComboBox to your KgGmObj object. This means that the Framework is going to try to find a property named RockDensity_Unit in that object. I also see another potential problem in your definition of this property.

为了从用户控件 XAML绑定到其code后面,你需要使用的DependencyProperty 。您可以了解如何在实现这些从依赖项属性概述页面MSDN。因此,首先,我建议您实施 RockDensity_Unit 属性作为的DependencyProperty

In order to bind from a UserControl xaml to its code behind, you need to use a DependencyProperty. You can find out how to implement these from the Dependency Properties Overview page at MSDN. So first, I would recommend that you implement your RockDensity_Unit property as a DependencyProperty.

接下来,我们必须找到一种办法从组合框在XAML的财产......我们能够做到这一点使用的RelativeSource 这样的绑定:

Next, we have to find a way to that property from the ComboBox in the xaml... we can do that using a RelativeSource binding like this:

<ComboBox DataContext="{StaticResource KgGmObj}" ItemsSource="{Binding KgGmList}" 
SelectedItem="{Binding RockDensity_Unit, RelativeSource={RelativeSource Mode=
FindAncestor, AncestorType={x:Type ucStep2}}, Mode=TwoWay}" />

现在,如果你有一个的DependencyProperty 绑定到的SelectedItem 财产和你的用户控件类被命名为 ucStep2 ,这应该所有的工作...让我知道如何去。

Now, if you have a DependencyProperty to bind to the SelectedItem property and your UserControl class is named ucStep2, this should all work... let me know how it goes.

更新2 >>>

您的错误是因为你必须在你的XAML文件的顶部...像这样添加一个XML命名空间:

Your error is because you have to add an XML namespace at the top of your XAML file... something like this:

xmlns:YourNamespace="clr-namespace:ApplicationName.FolderNameContainingClass"

然后你用它来引用您的类是这样的:

Then you use it to reference your class like this:

...AncestorType={x:Type YourNamespace:ucStep2} ...

此外,在你的的DependencyProperty 声明,你应该提供名称的的控制,而不是用户控件,所以更改

Also, in your DependencyProperty declaration, you're supposed to supply the name the type of your control, not UserControl, so change

Register("RockDensity_Unit", typeof(string), typeof(UserControl),

Register("RockDensity_Unit", typeof(string), typeof(NameOfYourUserControl),

显然与...你们班的实际名称,它扩展了用户控件

这篇关于WPF绑定COMBOX不同的目录,不同的SelectedValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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