简体   繁体   中英

WPF - Content of two user controls bound to same instance of control

I have a wpf/c# application.; I have a list box and according to the selected item I display a certain view. I have one view for all and different values displayed. The view looks like this:

<UserControl.Content>
    <Binding Path="DisplayControl" UpdateSourceTrigger="PropertyChanged"/>
</UserControl.Content>

The DisplayControl is a UserControl in the View Model of the list box item (I know it's not the best but that can't change for now). It is shared between all listbox items. The last listbox item (the last one that the DisplayControl set property was called for) is the one that shows the view when it is clicked - all the others show blank.

What is the problem? They are bound the same way, why does the last one only display the control and how do I fix this?

A control in WPF can have only one parent at a time. In fact, it can only be in one PLACE at one time. You are giving DisplayControl two different parents in rapid succession. The second one is where it ends up.

What are you actually trying to accomplish here? In program spec terms, not "I'm trying to pound a nail with a live dog because the birthday cake didn't work as a shovel". Do you want the content of DisplayControl to be shown in two different places at once? That's workable.

Anyway, first order of business is not to store any UserControls in your viewmodel. That can and must change. You're putting some kind of content in the UserControl, right? That's what it's there for, right? So have the content in your viewmodel, and display it in one or more UserControls in the view using a template.

The more time you waste trying to get this plumber's nightmare to work, the worse it'll get. The Sunk Cost Fallacy is not your friend. But for most people, there's only one way to learn that.

I think you should try something like this:

ViewModel.cs

public TypeModel
{
    private string _label;
    public string Label{ MVVM stuff}

    private UserControl _userControl;
    UserControl UserControl { MVVM stuff }
}

public class toto
{
private ObservableCollection<TypeModel> _list;
public ObservableCollection<TypeModel> List
{
get{return this._list;}
set { set value and notifyPropertyChanged }
}

private TypeModel _selectedItem;
public TypeModel SelectedItem
{
get{ return this._selectedItem;}
set { set value and NotifyPropertyChanged }
}

}

In your view.xaml

<listbox normal binding to List + selectedItem binding>
<ContentControl Binding={SelectedItem.UserControl} >

This is only pseudo code, try to stick to your existing code like this :)

Btw: @Ed Plunkett is right.

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