我正在创建一个自定义DataGrid控件,它具有一个属性ShowCloneColumn。如果将此属性设置为true,则DataGrid应添加另一个带有Button的列。
我创建的类派生自DataGrid并实现了一个依赖属性ShowCloneColumn。
public static readonly DependencyProperty ShowCloneColumnProperty =
DependencyProperty.Register("ShowCloneColumn",
typeof(bool),
typeof(CloneRowDataGrid),
new FrameworkPropertyMetadata(false,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
OnShowCloneColumnPropertyChanged));
public bool ShowCloneColumn
{
get { return (bool) GetValue(ShowCloneColumnProperty); }
set { SetValue(ShowCloneColumnProperty, value); }
}
在Generic.xaml中,我有以下样式。
<!-- Somewhere in here a button column should be declared? -->
<Style TargetType="{x:Type uiControls:CloneRowDataGrid}" BasedOn="{StaticResource {x:Type DataGrid}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type uiControls:CloneRowDataGrid}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
<ControlTemplate.Triggers>
<Trigger Property="ShowCloneColumn" Value="True">
<!-- Show clone column, a column with a button -->
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我对模板和自定义控件的关注度不是很高,所以我不确定在哪里添加按钮列,以便当有人使用CloneRowDataGrid并将依赖项属性ShowCloneColumn设置为true时它会显示。
答案 0 :(得分:0)
我必须从Generic.xaml样式中删除DataGrid的部分才能正确布局并在代码中创建列。
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
CloneColumn.Visibility = ShowCloneColumn ? Visibility.Visible : Visibility.Hidden;
}
private DataGridTemplateColumn _cloneColumn;
private DataGridTemplateColumn CloneColumn
{
get
{
if (_cloneColumn == null)
{
_cloneColumn = new DataGridTemplateColumn
{
Header = string.Empty,
Visibility = ShowCloneColumn ? Visibility.Visible : Visibility.Hidden
};
FrameworkElementFactory buttonFactory = new FrameworkElementFactory(typeof (Button));
buttonFactory.SetValue(Button.ContentProperty, "Clone");
buttonFactory.AddHandler(Button.ClickEvent, new RoutedEventHandler(CloneButtonClicked));
DataTemplate textTemplate = new DataTemplate {VisualTree = buttonFactory};
_cloneColumn.CellTemplate = textTemplate;
Columns.Add(_cloneColumn);
}
return _cloneColumn;
}
}