0

问题是 DependencyProperty 没有被分配给 XAML 中指定的值:

我有两个不同的用户控件,比如说 UserControl1 和 UserControl2,它们定义了两个控件共有的另一个用户控件:

用户控件1.xaml:

<modulename:MyUserControl ....somecode... DataOrientation="Horizontal"> 
</modulename:MyUserControl>

用户控件2.xaml

<modulename:MyUserControl ....somecode... DataOrientation="Vertical"> 
</modulename:MyUserControl>

两个 UserControl 之间的区别在于 UserControl1 必须使用水平方向显示数据,而 UserControl2 必须使用垂直方向显示数据。

在 MyUserControl 后面的代码中,我定义了一个依赖属性,如下所示:

public static readonly DependencyProperty DataOrientationProperty = 
DependencyProperty.Register ("DataOrientation",typeof(String),typeof(MyUserControl));

public String DataOrientation 
{
   get {return (String)GetValue(DataOrientationProperty);}
   set { SetValue(DataOrientationProperty, value); }
}

这些是 MyUserControl.xaml 中的代码片段:

...
<StockPanel>
  <Grid Name="MyGrid" SizeChanged="MyGrid_SizeChanged">
    <Grid.ColumnDefinitions>
      <ColumnDefinitions Width="*"/>
      <ColumnDefinitions Width="100"/>
    </Grid.ColumnDefinitions>

    <ScrollViewer Name="MySV" Grid.Column="0" ....>
      <Grid Name="DetailGrid"/>
    </ScrollViewer>

    <Grid Grid.Column="1" .........>
    ......Some Option Data....
   </Grid>
  </Grid>
 </StockPanel>

这个想法是根据方向标志将 ColumnDefinitions 更改为 RowDefinitions 并将 Grid.Column 更改为 Grid.Rows :

如果标志为“Horizo​​ntal”,则 UserControl 并排显示“DetailsGrid”和“Option Data”网格,这意味着“DetailGrid”在 Column 0 中,“Option Data”Grid 在 Column 1 中。

如果标志为“垂直”,则用户控件在第 1 行显示“DetailGrid”,在第 0 行显示“选项数据”。

在这个问题上需要一些帮助。

先感谢您。

4

1 回答 1

1

两件事,使依赖属性具有更改的处理程序,并在调试器中验证该值实际上是使其进入用户控件。还要为用户控件设置一个默认值(下面使用“水平”),但您决定如何处理。

public string DataOrientation
   {
       get { return (string)GetValue(DataOrientationProperty); }
       set { SetValue(DataOrientationProperty, value); }
   }

   /// <summary>
   /// Identifies the DataOrientation dependency property.
   /// </summary>
   public static readonly DependencyProperty DataOrientationProperty =
       DependencyProperty.Register(
           "DataOrientation",
           typeof(string),
           typeof(MyClass),
           new PropertyMetadata("Horizontal",  // Default to Horizontal; Can use string.Empty
                                 OnDataOrientationPropertyChanged));

   /// <summary>
   /// DataOrientationProperty property changed handler.
   /// </summary>
   /// <param name="d">MyClass that changed its DataOrientation.</param>
   /// <param name="e">Event arguments.</param>
   private static void OnDataOrientationPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
       MyClass source = d as MyClass;  // Put breakpoint here.
       string value = (string)e.NewValue;
   }
于 2012-11-08T19:01:41.757 回答