[英]Datagrid change image in column with button when event CellEditEnding wpf
我有数据网格。 一列带有按钮:
<DataGrid x:Name="WordsDataGrid" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
AutoGenerateColumns="False" CellEditEnding="WordsDataGrid_CellEditEnding">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="X" Width="10" Binding="{Binding Status}"/>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Visibility="Visible" Height="16" Width="16" Click="Update_Click">
<Button.Content>
<Image x:Name="KeyName" Source="Resources/update.png" />
</Button.Content>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
我有其他带有文本框的列在 c# 中创建动态。
我想在捕获事件时更改按钮的图像:
private void WordsDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
var column = e.Column.DisplayIndex;
var row = e.Row.GetIndex();
}
我知道行和列,但我不知道如何从 WordsDataGrid 中取出我的按钮来执行以下操作:
button.Content = new Image
{
Source = new BitmapImage(new Uri(@"/Resources/toupdate.png", UriKind.Relative))
};
编辑:
我加
Source="{Binding ImageSource}" />
public string ImageSource { get; set; } = @"\Resources\update.png";
首先是xaml,然后是对象,然后我更改字符串。
我想在单击按钮时执行此操作,您可以使用按钮的单击事件:
private void Update_Click(object sender, EventArgs e)
{
(sender as Button).Content = new Image
{
Source = new BitmapImage(new Uri(@"/Resources/toupdate.png", UriKind.Relative))
};
}
如果来自数据网格的另一个单元格:
您应该将Button
的Source
属性绑定到数据对象的 source 属性并设置此属性,而不是尝试操作 UI 元素:
private void WordsDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
var index = ...;
var itemsSource = WordsDataGrid.ItemsSource as IList<YourClass>;
itemsSource[index].Uri = new Uri(@"/Resources/toupdate.png", UriKind.Relative);
}
XAML:
<Image x:Name="KeyName" Source="{Binding Uri}" />
确保 YourClass 实现 INotifyPropertyChanged 并引发更改通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.