[英]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.