在代码中绑定 WPF 用户控件 属性

Bind WPF user control property inside code

我有一个具有用户控件的 MainWindow.xaml 和一个 ToggleButton:

<ToggleButton x:Name="toggle" Content="Wait" />

此按钮设置 BusyDecorator 名为 IsBusyIndicatorShowing 的用户控件 属性,它按预期工作,只要用户单击切换按钮,它就会设置用户控件 属性:

<Window x:Class="MainWindow"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ctrls="clr-namespace:Controls"
    Title="Busy" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
        <RowDefinition Height="322*" />
        <RowDefinition Height="53*" />
        </Grid.RowDefinitions>

        <ToggleButton x:Name="toggle" Content="Show" Margin="228,12,255,397" />
        <ctrls:BusyDecorator  HorizontalAlignment="Center" VerticalAlignment="Center" IsBusyIndicatorShowing="{Binding IsChecked, ElementName=toggle}">
            <Image  Name="canvas" Stretch="Fill"  Margin="5" />
         </ctrls:BusyDecorator>
    </Grid>
</Window> 

我想在代码中绑定BusyDecorator的IsBusyIndicatorShowing属性。 为此,我在 xaml 中的用户控件中添加了 IsBusyIndicatorShowing="{Binding IsBusyIndicatorShowing}" like

<ctrls:BusyDecorator   HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="Actions" IsBusyIndicatorShowing="{Binding IsBusyIndicatorShowing}">
  ...

但我不知道热定义和设置属性里面的代码像

public bool doSomething()
    {
       //init
       //toggle user control
       BusyDecorator.IsBusyIndicatorShowing = true;
       //do stuff
       //toggle user control
       BusyDecorator.IsBusyIndicatorShowing = false;
       return true;
    }

它不起作用,因为它说

Error   2   An object reference is required for the non-static field, method, or property 'Controls.BusyDecorator.IsBusyIndicatorShowing.get'   

假设我正确理解你的问题,错误消息是你问题的关键。当您说 "BusyDecorator.IsBusyIndicatorShowing = true" 时,您正在使用 BusyDecorator class 定义(好像它是静态的),而不是您在 XAML.

中定义的实例

您应该能够命名您的 XAML 实例(注意 x:Name):

<ctrls:BusyDecorator x:Name="myBusyDecorator" HorizontalAlignment="Center" VerticalAlignment="Center" IsBusyIndicatorShowing="{Binding IsChecked, ElementName=toggle}">
            <Image  Name="canvas" Stretch="Fill"  Margin="5" />
         </ctrls:BusyDecorator>

然后您应该能够在代码中引用该实例并在您希望的任何事件中访问 属性:

myBusyDecorator.IsBusyIndicatorShowing = true;