My problem is when I'm adding command to button, which is located in ListBoxItem Style in Page.Reosources and click it, nothing happen. But if I add button in default grid, command will work.
XAML:
<Page x:Class="kkRedux.MVVM.View.SpecialView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:kkRedux.MVVM.View"
xmlns:viewModel="clr-namespace:kkRedux.MVVM.ViewModel"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="SpecialView">
<Page.DataContext>
<viewModel:SpecialViewModel />
</Page.DataContext>
<Page.Resources>
<Style TargetType="ListBoxItem" x:Key="DieStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid Margin="11">
<Button Content="Click Mey"
Width="100" Height="100"
Background="Black"
Command="{Binding DownloadCommand}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ItemsPanelTemplate x:Key="panelTemplate">
<WrapPanel />
</ItemsPanelTemplate>
</Page.Resources>
<Grid>
<!--ItemsSource ommited-->
<ListBox Name="specialListBox"
ItemContainerStyle="{StaticResource DieStyle}"
ItemsPanel="{StaticResource panelTemplate}"
Background="Transparent"/>
<!--this Command is working-->
<Button Content="Click"
Height="100" Width="100"
Command="{Binding DownloadCommand}"/>
</Grid>
</Page>
ViewModel:
internal class SpecialViewModel
{
public RelayCommand DownloadCommand { get; set; }
public SpecialViewModel()
{
DownloadCommand = new RelayCommand<string>(o => Download(o));
}
private void Download(string arg)
{
MessageBox.Show(arg);
}
}
P.S. Click's working fine, but I can't use it due to MVVM.
CodePudding user response:
Bind to the DataContext
of the parent Page
:
Command="{Binding DataContext.DownloadCommand,
RelativeSource={RelativeSource AncestorType=Page}}"
The default DataContext
the element in the ListBox
is the current item in the Items
collection of the ListBox
. That's why your binding doesn't work.