简体   繁体   English

Silverlight:如何进行数据绑定?

[英]Silverlight: How to do this data binding?

I have a control that displays information about an Foo object. 我有一个显示有关Foo对象的信息的控件。 I am doing data binding just fine. 我正在做数据绑定。 However, I have an AutocompleteTextBox in this control that needs an ItemsSource . 但是,我在此控件中有一个AutocompleteTextBox ,它需要一个ItemsSource The data exists in my app, but there's no reason for it to be available on each instance of Foo . 数据存在于我的应用程序中,但没有理由在每个Foo实例上都可用。 What is the preferred pattern here for dealing with it? 这里首选的处理方式是什么?

I have a static method on a different class that will return the list I want - Bar.GetNames() . 我在另一个类上有一个静态方法,该方法将返回我想要的列表Bar.GetNames() Is there some way I can call that from the XAML? 有什么方法可以从XAML调用吗? Or do I need to use a StaticResource ? 还是我需要使用StaticResource

I'm using Silverlight 4. 我正在使用Silverlight 4。

This could go a few different ways... 这可以采取几种不同的方式...

You could create a custom AutoCompleteTextBox which has the listing embedded (pulled from some static repository internal to the app, etc...) within the control. 您可以创建一个自定义AutoCompleteTextBox ,该控件在控件中嵌入了列表(从应用内部的静态存储库等中拉出)。

You could have the property on Foo that goes to a service or other middle man within the app to retrieve the data from a single location. 您可以在Foo上拥有该属性,该属性将提供给应用程序中的服务或其他中间人以从单个位置检索数据。

You can reference the static resource within XAML by... 您可以通过以下方式在XAML中引用静态资源:

Text={x:Static namespace:type}

...where namespace is the residing namespace of your type defined in XAML. ...其中名称空间是XAML中定义的您类型的驻留名称空间。

Unfortunately, you cannot reference static property in Silverlight XAML. 不幸的是,您不能在Silverlight XAML中引用静态属性。

I would suggest something like FooViewModel: 我建议像FooViewModel这样的东西:

class FooViewModel: AnyBasicViewModelAround {
     public Foo Model {get; set; }
     public ItemNames : IList<ItemEntry> { get { return Bar.GetNames(); }}
}

The simplest way would be to do it in codebehind, probably in AutoCompleteTextBox.Loaded event handler. 最简单的方法是在代码隐藏中执行此操作,可能在AutoCompleteTextBox.Loaded事件处理程序中。 Something like: 就像是:

void AutoCompleteTextBox_Loaded(object sender, EventArgs e)
{
    ((AutoCompleteTextBox)sender).ItemsSource = Bar.GetNames();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM