Question

In my view I'm using an ItemsControl to display several Buttons. The XAML for the ItemsControl is:

<ItemsControl ItemsSource="{Binding CustomDirectories, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource buttonConverter}}" Margin="2">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Vertical"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

In the ViewModel of my View I have an ICommand which can handle the Button-Click. I need the Command here, because I also need some other Properties here.

The Converter for creating the buttons is:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value is ObservableCollection<DVDDirectory>)
    {
        ObservableCollection<CustomDirectory> customDirectories = (ObservableCollection<CustomDirectory>)value;
        List<Button> buttons = new List<Button>();

        foreach (CustomDirectory customDirectory in customDirectories)
        {
            Button button = new Button
            {
                Margin = new Thickness(2),
                Width = 140,
                Height = 25,
                Content = Path.GetFileName(customDirectory.Path)
            };
            buttons.Add(button);
        }
        return buttons;
    }
    return value;
}

My question now is: How can I assign the command from the ViewModel to the Command in the Converter where the Buttons are created?

I tried to pass the DataContext of my View to the Converter as ConverterParameter, but there I get an BindingException.

Was it helpful?

Solution 2

I solved it by my own.

I just created a singelton-class where the Command of the ViewModel is passed in the constructor. At the moment the converter is called, the singelton already has the Command and the Converter can assign the command.

OTHER TIPS

You can access the DataContext of your View via ElementName Binding:

<ItemsControl Name="MyItemsControl">
    <ItemsControl.ItemTemplate>
        <DataTemplate>                    
            <Button Command="{Binding ElementName=MyItemsControl, Path=DataContext.MyCommand}" CommandParameter="{Binding}"></Button>                    
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The ConverterParameter must be a string and can not be databound.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top