简体   繁体   中英

Binding to Button in WPF DataGrid does not update

I have a DataGrid in my WPF app with columns that hold boolean values. I want to mirror the DataGridCheckBoxColumn but I want to change the checkbox into a colored textbox. So for a true value it will show a green "Pass" and for false a red "Fail". I've tried setting DataGridCheckBoxColumn.ElementStyle and also a DataGridTemplateColumn with a button inside but the bindings don't update. They are set fine when it's loaded but not when the item is updated. The data grid holds a collection of TestPointAttempts.

Here's my code for the template column with a button inside of it.

<DataGridTemplateColumn Header="Talk Out"  >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Content="{Binding TalkOut, Converter={StaticResource BoolToPassFailConverter}, Mode=TwoWay}" 
                                    Foreground="{Binding TalkOut, Converter={StaticResource BoolToGreenRedConverter}, Mode=TwoWay}" 
                                    Style="{StaticResource TestResultButtonStyle}" 
                                    Click="TalkOutButton_Click"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

I'm able to get the click event working and update the "TalkOut" value in code, but the button Text and Foreground do not update. In my viewmodel I have code to update the items. I grab the selected cell as a TestPointAttempt and pass it to the viewmodel to update. Here's my viewmodel code:

public void ToggleTestResult(TestPointAttempt tpa, bool inOutSwitch)
    {
        if (inOutSwitch)
        {
            tpa.TalkIn = !tpa.TalkIn;
            RaisePropertyChanged(() => tpa.TalkIn);
        }
        else
        {
            tpa.TalkOut = !tpa.TalkOut;
            RaisePropertyChanged(() => tpa.TalkOut);
        }
    }

And here's my testPointAttempt model:

 public class TestPointAttempt
{
    public string Id { get; set; }

    public int TestAttemptNumber { get; set; }

    public bool? TalkIn { get; set; }
    public bool? TalkOut { get; set; }
    ...
}

How do I get the cell to update on a change?

the TestPointAttempt needs to implement INotifyPropertyChanged and the setter needs to trigger the propertyChanged event.

Another alternative is to use Fody for that.

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