繁体   English   中英

事件 CellEditEnding wpf 时,Datagrid 使用按钮更改列中的图像

[英]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))
  };
}

如果来自数据网格的另一个单元格:

WPF DataGrid:如何访问 DataGridTemplateColumn 特定行中的 ComboBox?

您应该将ButtonSource属性绑定到数据对象的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM