Сетка данных изменяет изображение в столбце с кнопкой при событии CellEditEnding wpf - PullRequest
2 голосов
/ 24 марта 2020

У меня есть датагрид. Один столбец с кнопкой:

<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 в c#.

Я хочу изменить изображение для моей кнопки, когда событие catch:

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, к объекту и я меняю строку.

Ответы [ 2 ]

1 голос
/ 24 марта 2020

Вы должны связать свойство Source Button со свойством источника вашего объекта данных и установить это свойство вместо попыток манипулировать элементами пользовательского интерфейса:

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 и вызывает уведомления об изменениях.

1 голос
/ 24 марта 2020

Если вы хотите сделать это при нажатии вашей кнопки, вы можете использовать событие нажатия вашей кнопки:

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: как мне получить доступ к ComboBox в определенной c строке DataGridTemplateColumn?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...