我有以下问题。
如果我使用图像作为数据网格标题,则在切换可见性时会出现错误。
<DataGridTextColumn Header="{StaticResource Image_Link}" IsReadOnly="True">
错误:Bei dem angegebenen Element handelt es sich bereits um das logische untergeordnete Element eines anderen Elements。
到目前为止我发现的唯一解决方法是使用我的imageheadercolumns的特定图像创建一个ControlTemplate。
这个数据网格行为是一个错误吗?
编辑:由谷歌翻译的错误:指定的元素已经是另一个元素的逻辑子元素。
编辑:示例
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Button Content="Toggle" Click="Button_Click" Height="20" Width="40" HorizontalAlignment="Left"/>
<DataGrid Width="200">
<DataGrid.Columns>
<DataGridTextColumn x:Name="colImage" Header="{StaticResource AnyImage}">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
的ResourceDictionary:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image x:Key="AnyImage" Source="Home.png" x:Shared="false"/>
</ResourceDictionary>
Button.Click:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.colImage.Visibility = this.colImage.Visibility == Visibility.Visible
? Visibility.Collapsed
: Visibility.Visible;
}
答案 0 :(得分:1)
**编辑:删除之前无关的答案 **
您需要将图像放在列的headertemplate中。
工作示例代码
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<BitmapImage x:Key="Image_Link" UriSource="test.bmp" />
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Content="Button" Name="button1" Width="75" Click="button1_Click" />
<Grid Grid.Row="1">
<DataGrid Height="200" VerticalAlignment="Top">
<DataGrid.Columns>
<DataGridTextColumn x:Name="firstHeader" IsReadOnly="True">
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<Image Source="{StaticResource Image_Link}" />
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Grid>
</Window>
private void button1_Click(object sender, RoutedEventArgs e)
{
firstHeader.Visibility = firstHeader.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
答案 1 :(得分:0)
我不确定是什么导致了这种情况,但您可以尝试显式创建Image
控件以显示图像:
<DataGridTextColumn IsReadOnly="True">
<DataGridTextColumn.Header>
<Image Source="{StaticResource Image_Link}" />
</DataGridTextColumn.Header>
</DataGridTextColumn>