简单的Windows Phone用户控件数据绑定不起作用

时间:2012-03-17 14:01:04

标签: silverlight windows-phone-7

我遇到的问题应该是非常简单的数据绑定方案。我想绑定一个项目列表。我想创建一个用户控件将它放在ItemsControl的模板中,并将ItemsControl绑定到一些数据。我对一次数据绑定非常满意所以我有点希望避免学习依赖属性以及这个简单场景的所有数据绑定内容。

以下是用户控件的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控件(注释行)做同样的事情,一切正常。

如何实施这个简单的方案?

1 个答案:

答案 0 :(得分:3)

要使自定义控件上的属性“可绑定”,您必须使其成为依赖项属性。在这里查看我的答案,找到一个在自定义控件上执行此操作的简单示例:passing a gridview selected item value to a different ViewModel of different Usercontrol

public string SomeString
{
    get { return (string)GetValue(SomeStringProperty); }
    set { SetValue(SomeStringProperty, value); }
}
public static readonly DependencyProperty SomeStringProperty =
    DependencyProperty.Register("SomeString", typeof(string), typeof(TestControl),
    new PropertyMetadata(string.Empty, new PropertyChangedCallback(OnSomeStringChanged)));

private static void OnSomeStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ((TestControl)d).OnSomeStringChanged(e);
}

protected virtual void OnSomeStringChanged(DependencyPropertyChangedEventArgs e)
{
    //here you can do whatever you'd like with the updated value of SomeString
    string updatedSomeStringValue = e.NewValue;
}
相关问题