Search code examples
c#wpfxamlcomboboxitemtemplate

WPF Draw primitives in ComboBox


I am making program for representation of network graph. I have here many attributes for connection between two nodes. Actually I am trying make a combobox with types of dashes like in MS Word. My code of ComboBox:

<ComboBox ItemsSource="{Binding Dashes}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Canvas >
                <Line X1="0" Y1="0" X2="100" Y2="100" StrokeDashArray="{Binding Dash}"/>
            </Canvas>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Code behind:

private DoubleCollection _dash;
private List<DoubleCollection> _listOfDashes;

public DoubleCollection Dash
{
    get { return _dash; }
    set
    {
        _dash = value;
        OnPropertyChanged("Dash");
    }
}

public List<DoubleCollection> Dashes
{
    get { return _listOfDashes; }
    set
    {
        _listOfDashes = value;
        OnPropertyChanged("Dashes");
    }
}

After launch the program the ComboBox isn't empty (there is two selectable object) but items are empty. Where I am making a mistake?


Solution

  • You are binding the ItemsSource property to your ViewModel Dashes property. It means that every ItemTemplate can be bound on each element of the Dashes collection (i.e. a DoubleCollection).

    Try to change your XAML in this way:

    <ComboBox ItemsSource="{Binding Dashes}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Line X1="0" Y1="0" X2="100" Y2="0" StrokeDashArray="{Binding}" Stroke="Black" Margin="6" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    

    It means that each Line has its StrokeDashArray binded to each DoubleCollection that belongs to Dashes collection. So in this way:

    vm = new ViewModel();
    vm.Dashes = new List<DoubleCollection>();
    vm.Dashes.Add(new DoubleCollection());
    vm.Dashes[0].Add(2);
    vm.Dashes[0].Add(3);
    
    vm.Dashes.Add(new DoubleCollection());
    vm.Dashes[1].Add(1);
    vm.Dashes[1].Add(4);
    

    you will see two different lines in your ComboBox. I hope it can help you.