对ListView和DataContext有些烦恼 [英] Some irritations with ListView and DataContext

查看:144
本文介绍了对ListView和DataContext有些烦恼的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下C#和XAML代码:

I've wrote the following C# and XAML Code:

namespace ListViewExample1
{
public partial class MainWindow : Window
{
    public ObservableCollection<MyColleague> myCollegues = new ObservableCollection<MyColleague>();

    public MainWindow()
    {
        myCollegues.Add(new MyColleague() { Name = "Tim", Surname = "Meier" });
        myCollegues.Add(new MyColleague() { Name = "Martin", Surname = "Hansen" });
        myCollegues.Add(new MyColleague() { Name = "Oliver", Surname = "Drumm" });


        InitializeComponent();
    }

    public ObservableCollection<MyColleague> MyColleagues 
    {
        get { return this.myCollegues; }
    }
}

public class MyColleague
{
    public String Name { get; set; }

    public String Surname { get; set; }
}
}

XAML代码:

<Grid>
    <ListView ItemsSource="{Binding}" DataContext="{Binding RelativeSource={RelativeSource ListViewExample1:MainWindow}, Path=myCollegues}">
        <ListView.View >
            <GridView >
                <GridViewColumn Header="Name" Width="150" DisplayMemberBinding="{Binding Name}"/>
                <GridViewColumn Header="Surname" Width="150" DisplayMemberBinding="{Binding Surname}"/>
            </GridView>
        </ListView.View>
    </ListView> 
</Grid>

现在我需要设置数据文本,但在这一点上我有一些烦恼。哪个DataContext-Syntax是对的?

Now I need to set the datacontext, but at this point I have some irritations. Which DataContext-Syntax is right?

推荐答案

有几十种方法来设置 DataContext ;没有人本来就是正确的。

There are dozens of ways to set DataContext; no one is inherently right.

值得注意的是,没有理由在所有项目控件上设置 DataContext 如果您需要的是绑定一个属性( ItemsSource ,在这种情况下)。设置 DataContext 简化绑定多个属性,因为所有绑定使用相同的上下文。

It's worth noting that there's no reason to set DataContext on an items control at all if all you need is to bind one property (ItemsSource, in this case). Setting DataContext simplifies binding multiple properties, because all of the bindings use the same context.

如果你想做数据绑定没有任何代码隐藏(如您在评论中所说),您所选择的示例不是很好,因为您在代码隐藏中创建对象。尝试用无参数构造函数创建一个类,例如:

If you want to do data binding without any code-behind (as you said in a comment), the example you've chosen isn't very good, since you're creating the object in code-behind. Try creating a class with a parameterless constructor, e.g.:

public class MyColleagueCollection : ObservableCollection<MyColleague>
{
   public MyColleagueCollection()
   {
       Add(new MyColleague() { Name = "Tim", Surname = "Meier" });
       Add(new MyColleague() { Name = "Martin", Surname = "Hansen" });
       Add(new MyColleague() { Name = "Oliver", Surname = "Drumm" });
   }
}

然后你可以做:

<ListView>
   <ListView.ItemsSource>
      <local:MyColleagueCollection/>
   </ListView.ItemsSource>
   ...
</ListView>

或者您可以设置 DataContext ,将 ItemsSource 设置为{Binding}。或者在资源字典中创建对象,并使用 StaticResource 绑定。

Or you could set the DataContext, and set the ItemsSource to "{Binding}". Or create the object in a resource dictionary, and bind using StaticResource.

您还可以将集合创建为属性(不是字段,如x0r正确指出)的窗口类,并执行以下操作:

You could also create your collection as a property (not a field, as x0r correctly points out) of the Window class and do this:

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}"...

现在使 Window 本身是数据上下文对象,允许窗口中的任何元素直接绑定到其属性,而不使用 RelativeSource

which now makes the Window itself the data context object, allowing any element in the window to bind to its properties directly without using RelativeSource.

或者(我们完成不了了),你可以给窗口一个名字,然后通过名称绑定到它: / p>

Or (we're nowhere near done), you can give the window a name, and then bind to it by name:

<ListView ItemsSource=`{Binding ElementName=MyWindow, Path=MyCollection}"...

我们甚至不会使用 ObjectDataProvider

大多数人最终都在做这件事 - 这与你要去f的正确答案一样接近ind - 正在为主窗口创建视图模型类,在窗口的构造函数中实例化,并将窗口的 DataContext 设置为该对象。从那时起,主窗口显示的任何视图被绑定到该视图模型的属性。请参阅Josh Smith关于Model / View / ViewModel模式的文章,以获得一个非常好的工作示例。

What most people end up doing - this is as close to a "right" answer as you're going to find - is creating a view model class for the main window, instantiating it in the window's constructor, and setting the window's DataContext to that object. From that point on, any view that the main window displays is bound to a property of that view model. See Josh Smith's article on the Model/View/ViewModel pattern for a really good worked example.

绑定和数据上下文是非常通用的。这当然也意味着有很多事情你可以错了。它与领土一起。一旦你了解他们,你很少遇到真正的问题。

Binding and data contexts are incredibly versatile. This of course also means that there are a lot of things you can get wrong. It goes with the territory. Once you understand them, though, you rarely run into real problems.

这篇关于对ListView和DataContext有些烦恼的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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