WPF:如何将对象绑定到ComboBox [英] WPF: How to bind object to ComboBox

查看:206
本文介绍了WPF:如何将对象绑定到ComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试学习如何将对象绑定到各种类型的控件。在这种情况下,我想在我的对象中获取样本数据显示在ComboBox中。代码运行,但显示的代替值(David,Helen,Joe)是文本TheProtect.UserControls.Client)



XAML:(ucDataBindingObject.xaml) p>

 < UserControl x:Class =TheProject.UserControls.ucDataBindingObject
xmlns =http://schemas.microsoft .com / winfx / 2006 / xaml / presentation
xmlns:x =http://schemas.microsoft.com/winfx/2006/xaml
xmlns:d =http:// schemas .microsoft.com / expression / blend / 2008
xmlns:mc =http://schemas.openxmlformats.org/markup-compatibility/2006
Width =Auto
高度=Auto
mc:Ignorable =d>

< Grid Width =130
Height =240
Margin =0>

< ComboBox Width =310
Horizo​​ntalAlignment =Left
VerticalAlignment =Top
ItemsSource ={Binding Path = Clients}/> ;
< / Grid>
< / UserControl>

C#:ucDataBindingObject.xaml.cs

 使用系统; 
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
namespace TheProject.UserControls
{
public partial class ucDataBindingObject:UserControl
{

public List< Client>客户{get;组; }


public ucDataBindingObject()
{
Clients = new List< Client>();
Clients.Add(new Client(1,David)); // sample data
Clients.Add(new Client(2,Helen));
Clients.Add(new Client(3,Joe));


InitializeComponent();
this.DataContext = this;
}
}

C#Client.cs

 使用System; 
using System.Linq;

命名空间TheProject.UserControls
{
public class Client
{
public int ID {get;组; }
public string Name {get;组; }

public Client(int id,string name)
{
this.ID = id;
this.Name = name;
}
}
}


解决方案>

有几种方法告诉框架要显示什么



1)使用 DisplayMemberPath (这将显示命名属性):

 < ComboBox ItemsSource ={Binding Path = Clients}
DisplayMemberPath =Name
/>

2)在ComboBox上设置 ItemTemplate 这就像#1,除了允许你定义一个模板显示,而不只是一个属性:

 < ComboBox ItemsSource ={Binding Path = Clients}> 
< ComboBox.ItemTemplate>
< DataTemplate>
< Border BorderBrush =GreenBorderThickness =1Padding =5>
< TextBlock Text ={Binding Path = Name,StringFormat ='Name:{0}'}/>
< / Border>
< / DataTemplate>
< /ComboBox.ItemTemplate>
< / ComboBox>

3)添加 ToString()到源类。如果你总是想给一个给定的类显示相同的字符串,这是有用的。 (注意,默认的 ToString()只是类类型名称,这就是为什么你看到TheProtect.UserControls.Client。)

  public class Client 
{
// ...

public override string ToString()
{
return string.Format({0}({1}),Name,ID);
}
}

4)添加 DataTemplate 到XAML资源。这对于将给定类类型与更复杂或风格化的模板相关联非常有用。

 < UserControl xmlns:local =clr -namespace:TheProject.UserControls> 
< UserControl.Resources>
< DataTemplate DataType =local:Client>
< TextBlock Text ={Binding Name}/>
< / DataTemplate>
< /UserControl.Resources>

// ...

< / UserControl>


Trying to learn how to bind objects to various types of controls. In this instance, I want to get sample data in my object to appear in ComboBox. The code runs but what appears instead of values (David, Helen, Joe) is text "TheProtect.UserControls.Client")

XAML: (ucDataBindingObject.xaml)

<UserControl x:Class="TheProject.UserControls.ucDataBindingObject"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             Width="Auto"
             Height="Auto"
             mc:Ignorable="d">

    <Grid Width="130"
          Height="240"
          Margin="0">

            <ComboBox Width="310"
                      HorizontalAlignment="Left"
                      VerticalAlignment="Top"
                      ItemsSource="{Binding Path=Clients}" />
    </Grid>
</UserControl>

C#: ucDataBindingObject.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
namespace TheProject.UserControls
{
    public partial class ucDataBindingObject : UserControl
    {

        public List<Client> Clients { get; set; }


        public ucDataBindingObject()
        {
            Clients = new List<Client>();
            Clients.Add(new Client(1, "David")); // sample data
            Clients.Add(new Client(2, "Helen"));
            Clients.Add(new Client(3, "Joe"));


            InitializeComponent();
            this.DataContext = this;
        }
    }

C# Client.cs

using System;
using System.Linq;

namespace TheProject.UserControls
{
    public class Client
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public Client(int id, string name)
        {
            this.ID = id;
            this.Name = name;
        }
    }
}

解决方案

There are several ways to tell the framework what to display

1) Use DisplayMemberPath on the ComboBox (this will display the named property):

<ComboBox ItemsSource="{Binding Path=Clients}" 
          DisplayMemberPath="Name"
/>

2) Set ItemTemplate on the ComboBox. This is like #1, except allows you to define a template to display, rather than just a property:

<ComboBox ItemsSource="{Binding Path=Clients}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Green" BorderThickness="1" Padding="5">
                <TextBlock Text="{Binding Path=Name,StringFormat='Name: {0}'}" />
            </Border>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

3) Add a ToString() override to source class. Useful if you always want to display the same string for a given class. (Note that the default ToString() is just the class type name, which is why you see "TheProtect.UserControls.Client".)

public class Client
{
    // ...

    public override string ToString()
    {
        return string.Format("{0} ({1})", Name, ID);
    }
}

4) Add a DataTemplate to the XAML resources. This is useful for associating a given class type with a more complex or stylized template.

<UserControl xmlns:local="clr-namespace:TheProject.UserControls">
    <UserControl.Resources>
        <DataTemplate DataType="local:Client">
            <TextBlock Text="{Binding Name}" />
        </DataTemplate>
    </UserControl.Resources>

    // ...

</UserControl>    

这篇关于WPF:如何将对象绑定到ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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