2012-03-17 22 views
1

非常にシンプルなデータバインディングのシナリオになるべき問題があります。私はアイテムのリストをバインドしたい。私は、ItemsControlのテンプレートにそれを入れ、いくつかのデータにItemsControlをバインドするユーザーコントロールを作成します。私は完全に1回のデータバインディングに満足しています。この単純なシナリオでは、依存プロパティとすべてのデータバインディングのことを知ることを避けたいと思っていました。ここでシンプルな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コントロール(コメント行)で同じことをしようとすると、すべて正常に動作します。

この単純なシナリオをどのように実装できますか?

答えて

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; 
} 
+0

私はOWNERTYPE引数(typeof演算(LOGEVENTS))の代わりに、何が起こっビューモデルを持っていないので? – Stilgar

+0

LogEventsはカスタムユーザーコントロールのタイプです。そのため、あなたのTestControlと同じです。私の答えでは、あなたのSomeString依存関係プロパティがあなたのTestControlのコードビハインドのように見えるものの例を追加しました。 – KodeKreachor

+0

ありがとうございます。今はうまくいくようです。私はプロパティセッターのコントロール(いくつかのテキストとcolr)のビューを変更するつもりです。これを行うには、これが適切な場所であるかどうかを教えていただければ幸いです。 – Stilgar

関連する問題