Warm tip: This article is reproduced from stackoverflow.com, please click
wpf user-controls

make WPF combobox with checkbox user control with generic class

发布于 2020-04-03 23:49:39

I found many solutions but I am struggling with binding generic class with user-control AND in ViewModel .I want to make ComboBox with checkbox. This ComboBox will use generic class So I can reuse this user-control in entire application.

My question is: How do I bind this generic class with my actual View.xaml file for ComboBox.

This One is my user-control

<base:CheckedComboBox>
    <ComboBox.Resources>
        <Style TargetType="ComboBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ComboBoxItem">
                        <base:BaseCheckBox HorizontalAlignment="Center" Content="{Binding FilterDropDownItemModel.Title}" ToolTip="{Binding FilterDropDownItemModel.ToolTip}" IsChecked="{Binding FilterDropDownItemModel.IsSelected,UpdateSourceTrigger=PropertyChanged}">
                        </base:BaseCheckBox>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ComboBox.Resources>

</base:CheckedComboBox>

This one is my generic class model

public abstract class DropDownModel<T> : BaseModel
{
    private T _mysummary;
    public T MySummary
    {
        get { return _mysummary; }
        set
        {
            _mysummary = value;
            RaisePropertyChanged();
        }
    }

    private bool _isSelected;
    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            if (_isSelected != value)
            {
                _isSelected = value;
                RaisePropertyChanged();
            }
        }
    }

    /// <summary>
    /// Title
    /// </summary>
    public abstract string Title
    {
        get;
    }

    public abstract string ToolTip
    {
        get;
    }
  }
}
Questioner
Harmi
Viewed
54
Dean Chalk 2020-02-01 01:14

Your bindings are all wrong, it should look something like this:

    <Style TargetType="ComboBoxItem">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ComboBoxItem">
                    <base:BaseCheckBox HorizontalAlignment="Center" 
                                       Content="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext.FilterDropDownItemModel.Title}" ToolTip="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext.FilterDropDownItemModel.ToolTip}" IsChecked="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext.FilterDropDownItemModel.IsSelected}">
                </base:BaseCheckBox>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>