質問

I have created an attached property to be added to UserControls. This attached property requires a binding, and this binding requires a converter.

As the resources are set after the UserControl declaration I'm looking a way to declare the attached property after the resource creation. How can I do that?

An example, if I define a background as a static resource I cannot set the background on the control creation but after the resources creation:

<UserControl ...
             ...
             ...>

<UserControl.Resources>
    background color declared
</UserControl.Resrouces>

<UserControl.Background>
    usage of the StaticResource here is valid.
</UserControl.Background>

So I want to the same with an attached property that I woudl normaly define as:

<UserControl xx:MyAttachedProperty.Bla="{Binding A}" >

But as I need a converter I want to specify it after the resources.

Hope it's clear. Thanks.

役に立ちましたか?

解決 2

You can define yourConverter as a resource one hierarchy up either as a part of Window or Appand than you can use it just like you intended to.

Moreover moving common resources up to App level give you advantage of re-usability which different User controls can share. Move your converter to App.xaml -

<App.Resources>
  <!-- Your converter here -->
</App.Resources>

他のヒント

You can use a ResourceDictionary.

Just add it in the solution explorer with Add -> Resource dictionary

Declare your Converter there like

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <BooleanToVisibilityConverter x:Key="BooleanToVisibility" />

</ResourceDictionary>

In your XAML, you can use it like

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

Now you can use your Converter anywhere where you have your Resource Dictionary

If you only need your Converter in your UserControl (as you mentioned in the Comment above), then you can still declare it like:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyResources.xaml" />
            <ResourceDictionary>
                <BooleanToVisibilityConverter x:Key="MyConverter" />
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

I just used BooleanToVisibilityConverter for the example, but it is easy to use your own converter there.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top