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

时间:2015-08-19 13:38:47

标签: c# wpf user-controls

我有一个MainWindow.xaml,它有一个用户控件和一个ToggleButton

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

此按钮设置BusyDecorator用户控件属性IsBusyIndicatorShowing,它按预期工作,只要用户点击toggLe按钮,它就会设置用户控件属性:

<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}",如

<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'   

1 个答案:

答案 0 :(得分:1)

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

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

<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;