使用事件处理程序更改按钮的内容

时间:2012-04-03 12:40:32

标签: wpf button

代码包含datagrid中的按钮。每个都包含文本“发送”。

<DataGrid.Columns>
    <DataGridTextColumn Width="*" 
                        Header="Uid" 
                        Binding="{Binding Uid}"/>
    <DataGridTextColumn Width="*" 
                        Header="Type" 
                        Binding="{Binding Type}"/>
    <DataGridTextColumn Width="*" 
                        Header="ChannelType" 
                        Binding="{Binding ChannelType}"/>

    <DataGridTemplateColumn Width="*">

    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Name="btnSend" Click="btnSend_Click">Send</Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

单击此按钮时,文本“发送”应更改为“取消”。我怎么能这样做?

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    //If I click first button, only first button should be changed
    //from "Send" to "Cancel"
    //Rest button should remain as "Send"
}

1 个答案:

答案 0 :(得分:0)

又快又脏:

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    changeBtnText((Button)sender, "Cancel");
}

private void changeBtnText(Button button, String text)
{
    if (Button.Dispatcher.CheckAccess())
    {
        button.Content = text;
    }
    else
    {
        Button.Dispatcher.BeginInvoke(()=>
        {
            changeBtnText(button);
        });
    }
}

您需要在修改UI时将命令放在Dispatcher-Queue中,只允许Dispatcher执行此操作。