每当单元格获得焦点时,我需要扩展器进行扩展。
除此之外,我希望扩展器在细胞失去焦点时收缩。
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Expander VerticalAlignment="Stretch"
IsExpanded="{Binding Path=IsFocused,
Mode=OneWay,
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType=DataGridCell},
UpdateSourceTrigger=LostFocus}">
<!--Expander.Content-->
</Expander>
</DataTemplate>
</DataGirdTemplateColumn.CellTemplate>
该解决方案只是在扩展,而不是收缩。
我错在哪里?
笔记:
DataGrid.SelectionMode="Single"
DataGrid.SelectionUnit="Cell"
单击"这个解决方案只是在扩大,而不是收缩。
扩展器将其展开一次,然后尝试单击DataGridcell中的其他位置,它将不起作用,第一次手动扩展时绑定将被销毁,并且当DataGridCell IsFocus为真时,扩展器将不会自动扩展。 如果在视图模型中对简单布尔属性使用单向绑定,也会发生同样的情况。
编辑:
尝试使用此扩展器,我相信它可能正是您需要的:
.xaml
<local:MyExpander DataGridCellToObserve="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell}}" >
。.cs
public class MyExpander : Expander
{
public MyExpander()
{
this.IsEnabled = false;
}
public DataGridCell DataGridCellToObserve
{
get { return (DataGridCell)GetValue(DataGridCellToObserveProperty); }
set { SetValue(DataGridCellToObserveProperty, value); }
}
public static readonly DependencyProperty DataGridCellToObserveProperty =
DependencyProperty.Register("DataGridCellToObserve", typeof(DataGridCell), typeof(MyExpander), new PropertyMetadata(test));
private static void test(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
(e.NewValue as DataGridCell).Selected += (d as MyExpander).setExpanded;
(e.NewValue as DataGridCell).Unselected += (d as MyExpander).setExpandedFalse;
}
private void setExpanded(object sender, RoutedEventArgs e)
{
this.SetValue(IsExpandedProperty, true);
this.IsEnabled = true;
}
void setExpandedFalse(object sender, RoutedEventArgs e)
{
this.SetValue(IsExpandedProperty, false);
this.IsEnabled = false;
}
}
下面是一个依赖项较少的解决方案(如果您尚未使用混合行为(:
<Expander Header="Hello" Content="Goodbye">
<Expander.Style>
<Style TargetType="Expander">
<Style.Triggers>
<EventTrigger RoutedEvent="LostFocus">
<EventTrigger.Actions>
<BeginStoryboard>
<BeginStoryboard.Storyboard>
<Storyboard TargetProperty="IsExpanded">
<BooleanAnimationUsingKeyFrames>
<DiscreteBooleanKeyFrame Value="False" KeyTime="0" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard.Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="GotFocus">
<EventTrigger.Actions>
<BeginStoryboard>
<BeginStoryboard.Storyboard>
<Storyboard TargetProperty="IsExpanded">
<BooleanAnimationUsingKeyFrames>
<DiscreteBooleanKeyFrame Value="True" KeyTime="0" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard.Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</Expander.Style>
</Expander>