在WPF中单击按钮时更改绑定对象属性

时间:2010-08-31 12:08:20

标签: wpf data-binding

我已将对象绑定到WPF控件。如何单击编辑按钮仅使用xaml而不使用代码切换对象属性“IsEditMode”?以下是xaml的示例代码 -

<Label Style="{StaticResource TitleLabel}" 
       Content="{Binding Path=GroupTitle}" 
       Visibility="{Binding Path=IsEditMode, Converter={StaticResource boolToVis}}"
       HorizontalAlignment="Left" />

<Button Content="Edit" HorizontalAlignment="Right" VerticalAlignment="Center">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <!--Toggle the bindedobject.IsEditMode property of click of button-->
        </EventTrigger>
    </Button.Triggers>
</Button>

2 个答案:

答案 0 :(得分:1)

  

仅使用xaml而后面没有代码

我认为完全没有C#(或VB)代码是可能的,但你可以使用MVVM pattern完成没有代码隐藏的代码。所以你拥有C#代码,而不是代码隐藏......

如果你这样做,你需要从ViewModel公开一个命令:

    private DelegateCommand _enterEditModeCommand;
    public ICommand EnterEditModeCommand
    {
        get
        {
            if (_enterEditModeCommand== null)
            {
                _enterEditModeCommand= new DelegateCommand(EnterEditMode);
            }
            return _enterEditModeCommand;
        }
    }

    private void EnterEditMode()
    {
        IsEditMode = true;
    }

将按钮绑定到该命令:

<Button Content="Edit" Command="{Binding EnterEditModeCommand}"
        HorizontalAlignment="Right" VerticalAlignment="Center">

答案 1 :(得分:0)

框架中已有控件:

<Label Style="{StaticResource TitleLabel}" 
       Content="{Binding Path=GroupTitle}" 
       Visibility="{Binding Path=IsEditMode, Converter={StaticResource boolToVis}}"
       HorizontalAlignment="Left" />

<ToggleButton Content="Edit" HorizontalAlignment="Right" VerticalAlignment="Center"
       IsChecked="{Binding IsEditMode}"/>