Bind a string in xaml to a property

2019-09-05 08:59发布

问题:

I have a public constant string on my view model that I want to bind to the

sys:string

inside the xaml snippet below:

<ComboBox.ItemsSource>
    <CompositeCollection>
       <sys:String></sys:String>
       <CollectionContainer Collection="{Binding VMCollection, Source={StaticResource proxy}}" />
    </CompositeCollection>
 </ComboBox.ItemsSource>

It would be easy if String had a content property or something, but just trying to figure out the best way to do this.

回答1:

Personally, I think it looks like you should be combining these options (that are available) in your ViewModel anyway. (Aren't these the options that should be "presented" to the user? even if you create an entire new UI for this, will the options be the same?)

But to answer your question..

<Window ...
...
xmlns:local="clr-namespace:MyNamespace">

<ComboBox>
        <ComboBox.ItemsSource>
            <CompositeCollection>
                <x:StaticExtension Member="local:Constants.MyConst" />
                <core:String>1</core:String>
                <core:String>2</core:String>
                <core:String>3</core:String>
            </CompositeCollection>
        </ComboBox.ItemsSource>
    </ComboBox>

public static class Constants
{
    public static string MyConst
    {
        get
        {
            return "asd";
        }
    }
}

This works