-->

TwoWay Binding of a ComboBox to a static property

2019-03-04 11:10发布

问题:

Well, i just posted this question, but i figured that i am not doing anything wrong. My code (and the code of all of the answers) is correct, but my dev-maschine runs with .NET4.5 which apparently has a problem with the binding of the combobox...

So here a new version of the question: How to two-way bind a combobox's SelectedItem to a static Property in .NET4.5?

The following code snippets work in .net4 but not in .NET4.5. In 4.5 it is just that the selected value is not propagated back into my static property.

My ViewModel:

public class MainWindowViewModel
{
    public static List<String> MyElements { get; set; }
    public static string SelectedElement { get; set; }

    static MainWindowViewModel()
    {
        MyElements = new List<string>() {"a", "b", "c"};
        SelectedElement = "a";
    }
}

And my XAML

<Window.Resources>
    <me:MainWindowViewModel x:Key="model"/>
</Window.Resources>

<StackPanel>
    <ComboBox
        ItemsSource="{Binding Source={x:Static me:MainWindowViewModel.MyElements}, Mode=OneWay}"
        SelectedItem="{Binding Source={StaticResource model}, Path=SelectedElement}" />
</StackPanel>

Does anybody have an idea how to achieve this two-way binding of a ComboBox's SelectedItem to a static Property in .NET4.5?

回答1:

Please refer to my report on Microsoft Connect. Every Selector control is infected by this issue.

Finally, a few weeks ago Microsoft released an appropriate patch which has already been distributed through Windows Update. see Knowledge Base KB2805222 (WPF - Issue 7)

WPF - Issue 7: Assume that you change a selector property (such as, the SelectedItem property) or ComboBox.Text property by using a binding path that contains a static property. In this situation, the binding does not react to the changes. Specifically, the new value is not written to the data item.