【问题标题】:Datagrid change image in column with button when event CellEditEnding wpf事件CellEditEnding wpf时,Datagrid使用按钮更改列中的图像
【发布时间】:2020-03-24 11:00:26
【问题描述】:

我有数据网格。一列是带按钮的:

<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,再到object,然后我更改字符串。

【问题讨论】:

  • 点击按钮时是否要这样做?
  • 不,我想在写 WordsDataGrid_CellEditEnding 时这样做。按钮在列索引 = 6 中。所以当行 = 4 时,我想以单元格为例 [4,6] 并在按钮上投射。

标签: c# wpf


【解决方案1】:

您应该将ButtonSource 属性绑定到数据对象的源属性并设置此属性,而不是尝试操作 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 并引发更改通知。

【讨论】:

    【解决方案2】:

    我想在单击按钮时执行此操作, 您可以使用按钮的点击事件:

    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: How do I access a ComboBox in a specific row of a DataGridTemplateColumn?

    【讨论】:

    • 不,我不想要。我想在更新其他列时这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 2016-03-19
    相关资源
    最近更新 更多