2012-05-30 3 views
0

У меня возникла проблема в моем приложении, и я не могу пройти мимо нее. Для иллюстрации ситуации я создал следующее простое приложение WPF.WPF Binding и DataTemplate

MainWindow.xaml:

<Window x:Class="GlobalDataTemplate.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:my="clr-namespace:GlobalDataTemplate" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <DataTemplate DataType="{x:Type my:MyData}"> 
      <StackPanel Background="{Binding BgColor}"> 
       <TextBlock Text="{Binding Text}"/> 
       <TextBlock Text="{Binding Number}"/> 
      </StackPanel> 
     </DataTemplate> 
    </Window.Resources> 
    <ItemsControl> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <UniformGrid Columns="3" /> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
     <my:MyData x:Name="NW" Text="NW" Number="1" BgColor="#FFFF0000" /> 
     <my:MyData x:Name="N" Text="N" Number="2" BgColor="#FF63FF00" /> 
     <my:MyData x:Name="NE" Text="NE" Number="3" BgColor="#FFFFCA00" /> 
     <my:MyData x:Name="W" Text="W" Number="4" BgColor="#FF0037FF" /> 
     <my:MyData x:Name="C" Text="C" Number="5" BgColor="#FF9E00FF" /> 
     <my:MyData x:Name="E" Text="E" Number="6" BgColor="#FF838383" /> 
     <my:MyData x:Name="SW" Text="SW" Number="7" 
        BgColor="{Binding ElementName=NW, Path=BgColor}" /> 
     <my:MyData x:Name="S" Text="S" Number="8" 
        BgColor="{Binding ElementName=N, Path=BgColor}" /> 
     <my:MyData x:Name="SE" Text="SE" Number="9" 
        BgColor="{Binding ElementName=NE, Path=BgColor}" /> 
    </ItemsControl> 
</Window> 

MyData.cs:

using System.Windows; 
using System.Windows.Media; 

namespace GlobalDataTemplate 
{ 
    class MyData : DependencyObject 
    { 
     public string Text 
     { 
      get { return (string)GetValue(TextProperty); } 
      set { SetValue(TextProperty, value); } 
     } 
     public static readonly DependencyProperty TextProperty = 
      DependencyProperty.Register("Text", typeof(string), typeof(MyData), new UIPropertyMetadata(null)); 

     public int Number 
     { 
      get { return (int)GetValue(NumberProperty); } 
      set { SetValue(NumberProperty, value); } 
     } 
     public static readonly DependencyProperty NumberProperty = 
      DependencyProperty.Register("Number", typeof(int), typeof(MyData), new UIPropertyMetadata(0)); 

     public Brush BgColor 
     { 
      get { return (Brush)GetValue(BgColorProperty); } 
      set { SetValue(BgColorProperty, value); } 
     } 
     // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty BgColorProperty = 
      DependencyProperty.Register("BgColor", typeof(Brush), typeof(MyData), new UIPropertyMetadata(null)); 
    } 
} 

Из XAML, можно было бы ожидать, чтобы увидеть 3x3 сетку с теми же цветами через дно, как показывает через вершину , Но ни один из цветов для нижней строки не отображается вообще (вы видите белый фон окна). Как я могу получить цвета внизу, чтобы правильно привязать цвета вверху?

Я также попытался добавить свойство измененного обработчика и установить точку останова. Точка прорыва никогда не попадает.

Заранее спасибо.

+0

Я предполагаю, что выцветшие? – CodingGorilla

+0

Возможно, вам потребуется установить свойство Rows на UniformGrid: Ross

+0

@CodingGorilla, по сути, да, они неокрашенные. Как я уже упоминал, вы видите белый фон окна. – gregsdennis

ответ

1

Когда я запускаю свой код, я получаю сообщение об ошибке в отладочный вывод:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=BgColor; DataItem=null; target element is 'MyData' (HashCode=65325907); target property is 'BgColor' (type 'Brush')

И.Э. это означает, что WPF не рассматривает элементы MyData как часть логического дерева. Следовательно, выведите MyData из Freezable, например.

class MyData : Freezable 
{ 
    protected override Freezable CreateInstanceCore() 
    { 
     throw new System.NotImplementedException(); 
    } 

    ... put the dependency properties here ... 

} 

«Нельзя найти правящую FrameworkElement ...» проблема связана с «наследования контекстов»; подробности здесь: http://blogs.msdn.com/b/nickkramer/archive/2006/08/18/705116.aspx.

+0

Спасибо за это. Сегодня я чему-то научился. Работает как шарм! – gregsdennis