简体   繁体   中英

Change the assigned function and text to a button in a WPF Datagrid depending on column value

I have this button inside a column:

<DataGridTemplateColumn>
       <DataGridTemplateColumn.CellTemplate>
              <DataTemplate>
                     <Button Click="UpdateTopic">Update</Button>
              </DataTemplate>
       </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

But now I require that both the text in it and the function applied to it to change according to the value in one of my column. How can I achieve this?

Create a property in your code behind or view model and bind it to the Button.Content property:

<Button Click="UpdateTopic" Content={Binding ButtonText}" />

Assuming that you have access to your data objects bound to the DataGrid as the column value changes, edit the method in your code behind that is linked to the Button.Click event to something like this:

public void UpdateTopic()
{
    if (columnValue == "Something") DoSomething();
    else if (columnValue == "SomethingElse") DoSomethingElse();
    else if (columnValue == "AnotherThing") DoAnotherThing();
}

This way, you can have one click handler that performs a variety of duties dependant on the current value of the column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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