[英]How to bind a dependency object inside a wpf datagrid to a observable collection
背景:我有一個wpf數據網格,它具有一個自定義類( CustomTextBox
),該類繼承自TextBox
。 我已經在這個自定義類中創建了一個依賴對象( ValueProperty
),因此我可以綁定到它。 我還有一個可觀察的集合,用作DataGrid
的DataSource
。
問題:問題是,當我將自定義類的依賴項屬性綁定到可觀察集合中的公共屬性時, DataGrid
沒有任何顯示。
這是發生綁定的DataGrid
TemplateColumn
的xaml :
<DataGridTemplateColumn Header="Drawing Location" Width="240" CellStyle="{StaticResource dataGridCellStyle}">
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<Label Content="Drawing Location" Width="230" HorizontalContentAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CustomTextBox:CustomTextBox x:Name="ftbDrawingX" Value="{Binding DrawingLocationX, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource textBox}" Width="85" Behavior="DistanceCombinedFtIn"/>
<Label Content=","/>
<CustomTextBox:CustomTextBox x:Name="ftbDrawingY" Value="{Binding DrawingLocationY, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource textBox}" Width="85" Behavior="DistanceCombinedFtIn"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
這是自定義類中的依賴項屬性:
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(CustomTextBox),
new FrameworkPropertyMetadata(0D, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.AffectsRender, new PropertyChangedCallback(ValueProperty_OnTextPropertyChanged)));
public double Value
{
get {return (double)this.GetValue(ValueProperty);}
set
{
}
}
在后面的代碼中:
private ObservableCollection<CustomItem> data = new ObservableCollection<CustomItem>();
this.dgTakeoffDataGrid.ItemsSource = data;
CustomItem
對象實現INotifyPropertyChanged
並具有兩個屬性: DrawingLocationX
和DrawingLocationY
。
任何人都可以看看我是否做錯了。 我的DataGrid
空了,我知道我的問題是綁定到依賴項對象。 感謝您的幫助。
編輯:我從Value的setter屬性中刪除了所有邏輯,並添加了一個回調方法來處理對依賴對象的更改,還更新了它的Text屬性。
private static void ValueProperty_OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs eventArgs)
{
CustomTextBox box = d as CustomTextBox;
if (box != null)
{
box.value = Conversions.RoundLeastSignificant(Conversions.RoundLeastSignificant((double)eventArgs.NewValue));
box.Text = Conversions.FormatReadTextValue((double)eventArgs.NewValue, box.behavior, box.acadDocument);
}
}
我設法解決了這個問題。 解決方案是我的最后一條評論:解決方案是從屬性的設置器中刪除所有邏輯,並處理在注冊依賴項屬性時定義的CallBack方法中的設置Value。
這是一般的解決方案。 希望它也能幫助其他人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.