簡體   English   中英

DependencyProperty的值不會從XAML傳播到后面的代碼

[英]The value of DependencyProperty is not propagated from XAML to code behind

問題是DependencyProperty沒有分配給XAML中指定的值:

我有兩個不同的用戶控件,比如說UserControl1和UserControl2,它們定義了兩個控件共有的另一個用戶控件:

UserControl1.xaml:

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

UserControl2.xaml

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

兩種UserControl的區別在於,UserControl1必須使用“水平方向”顯示數據,而UserControl2必須使用“垂直方向”顯示數據。

在MyUserControl的代碼內部,我定義了一個Dependency屬性,如下所示:

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”在第0列中,而“ Option Data”網格在第1列中。

如果標記為“ Vertical”,則UserControl在第1行中顯示“ DetailGrid”,在第0行中顯示“ Option Data”。

在這個問題上需要一些幫助。

先感謝您。

兩件事情,使dependency屬性的處理程序發生更改,並在調試器中驗證該值實際上已在用戶控件中使用。 還要為用戶控件設置一個默認值(以下使用“水平”),但是您可以決定如何處理它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM