【发布时间】:2018-09-13 15:04:56
【问题描述】:
背景:
我有一个 wpf 数据网格,它有一个继承自 TextBox 的自定义类 (CustomTextBox)。我在这个自定义类中创建了一个依赖对象(ValueProperty),所以我可以绑定到它。我还有一个可观察的集合,用作DataSource 的DataGrid。
问题:
问题是,当我将自定义类的依赖属性绑定到可观察集合中的公共属性时,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);
}
}
【问题讨论】:
-
您希望 DrawingLocationX 属性显示在哪里?在文本框中?您的“文本框”样式是如何定义的?
-
@mm8 我希望 DrawingLocationX 和 DrawingLocationY 显示在 CustomTextBox 控件中。如果您查看 Xaml,我将绑定到这两个。 Style 只是设置大小、背景颜色和占位符文本。
-
那么您为什么希望 TextBox 能够显示您的自定义属性的值...?你在哪里设置 Text 属性?
-
我对代码做了一些更改,请参阅编辑。我现在能够获取要显示的值,但并不是所有的值都在显示,这很奇怪。
标签: c# wpf data-binding datagrid dependency-properties