简体   繁体   中英

Bind WPF user control property inside code

I have a MainWindow.xaml that has a user control and a ToggleButton :

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

This button sets BusyDecorator User control property called IsBusyIndicatorShowing , it works as expected, whenever user clicks on toggLe button it sets user control property:

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

I want to bind BusyDecorator's IsBusyIndicatorShowing property in code. To do so I added IsBusyIndicatorShowing="{Binding IsBusyIndicatorShowing}" inside user control in xaml like

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

But I do not know hot to define and set property inside code like

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

It does not work because it says

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

The error message is the key to your problem, assuming I understand your question correctly. When you say "BusyDecorator.IsBusyIndicatorShowing = true" you are using the BusyDecorator class definition (as though it is static), not the instance you have defined in your XAML.

You should be able to name your XAML instance (note the 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>

Then you should be able to refer to that instance in code and access the property in whatever event you desire as such:

myBusyDecorator.IsBusyIndicatorShowing = true;

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