开发者

Accessing inner controls of UserControl

I am building a custom UserControl which would allow me to place text inside a ProgressBar. The problem is, none of the ProgressBar's DependencyProperties get transferred over. Here is the XAML for my custom UserControl.

<UserControl
    x:Class = "MyProgram.MyCustomProgressBar"
    xmlns   = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" >

    <Grid>
        <ProgressBar    Name="uiProgressBar"    />
        <Label          Nam开发者_StackOverflow中文版e="uiLabel"          />
    </Grid>
</UserControl>

How can I access and set the Minimum, Maximum, Value, etc. from XAML when I start using this UseControl.

<local:MyCustomProgressBar x:Name="uiLoadTime" ??.uiProgressBar.Maximum="50" />

I am hoping I don't need to redefine a bunch of DependencyProperties in order to get this functionality.


The usual way is to use a DependencyProperty... it's not so bad once you got used to it really.

Use the "propdp" built in snippet in the code-behind of your usercontrol.

Let's take the ProgressBar.Maximum example:

Make an integer dependencyproperty with a default value of 100 (or whatever you like), name it InnerProgressBarMax.

In your UserControl's XAML, you bind it this way:

<ProgressBar Maximum="{Binding InnerProgressBarMax, ElementName=myUsrCtrl}" />

When you use the control in another part of your application, simply enter a value like this:

<local:MyCustomProgressBar x:Name="uiLoadTime" InnerProgressBarMax="50" />

Rinse & repeat for each property you want to expose.

Edit: If you really need to have 50+ DP exposed, you could bring down the hastle by specifying smart default values for your DPs.

To do that, when you create a DP, set the parameter of new PropertyMetadata(YOUR_DEFAULT_VALUE)

Once that is done, your control may expose many DPs, but you'll only have to set a few manually in the XAML code that uses the control.


The alternative to wrapping everything in DependencyProperties is to let the UserControl's consumer provide the ProgressBar. It could look like this:

<local:MyCustomProgressBar x:Name="uiLoadTime"> <local:MyCustomProgressBar.ProgressBar> <ProgressBar Maximum="50" /> </local:MyCustomProgressBar.ProgressBar> </local:MyCustomProgressBar>

Then in MyCustomProgressBar.xaml.cs, you would expose a public property for a ProgressBar. In its setter, modify the properties however you see fit, then add it to the UserControl's root Grid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜