我有一个应该是非常简单的数据绑定场景的问题。我想绑定一个项目列表。我想创建一个用户控件把它放在一个ItemsControl的模板中,并将ItemsControl绑定到一些数据。我对一次数据绑定非常满意,所以我希望避免了解这个简单场景的依赖属性和所有数据绑定的内容。简单的Windows Phone用户控件数据绑定不起作用
下面是用户控件的XAML:
<TextBlock>Just Something</TextBlock>
而后面的代码:
namespace TestWindowsPhoneApplication
{
public partial class TestControl : UserControl
{
public TestData SomeProperty { get; set; }
public String SomeStringProperty { get; set; }
public TestControl()
{
InitializeComponent();
}
}
}
MainPage.xaml中:
<ItemsControl Name="itemsList" ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<t:TestControl SomeStringProperty="{Binding Path=SomeString}"></t:TestControl>
<!--<TextBlock Text="{Binding Path=SomeString}"></TextBlock>-->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
下面是MainPage.xaml.cs中:
namespace TestWindowsPhoneApplication
{
public class TestData
{
public string SomeString { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
itemsList.DataContext = new TestData[] { new TestData { SomeString = "Test1" }, new TestData { SomeString = "Test2" } };
}
}
}
当我运行该项目时,出现错误“参数不正确”。我也试着用SomeProperty = {Binding}直接绑定到该项目,因为这是我真正想要做的,但是这会导致相同的错误。如果我尝试用TextBlock控件(注释行)做同样的事情,一切正常。
我该如何实现这个简单的场景?
因为我没有一个ViewModel发生的事情在ownerType参数(typeof运算(LOGEVENTS))的地方吗? – Stilgar 2012-03-17 17:17:03
LogEvents是自定义用户控件类型,因此它将等同于您的TestControl。在我的回答中,我添加了一个示例,说明在您的TestControl的代码隐藏中您的SomeString依赖属性的外观。 – KodeKreachor 2012-03-17 17:19:57
谢谢。它现在似乎工作。我打算在属性设置器中更改控件的视图(一些文本和colr)。如果您告诉我这是否是正确的地方,我会非常感激。 – Stilgar 2012-03-17 17:28:58