给出这个xaml:
<ItemsControl Grid.Row="1" ItemsSource="{Binding Devices}">
<ItemsControl.ItemsPanel>
<itemspaneltemplate>
<UniformGrid Rows="1" />
</itemspaneltemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type viewModels:IDeviceViewModel}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}"
Grid.Row="0"
Margin="5"
HorizontalAlignment="Center" />
<ContentControl Grid.Row="1">
<ContentControl.Content>
<Binding Path="CurrentState">
<Binding.TargetNullValue>
<Button Command="{Binding DataContext.activateCommand,RelativeSource={RelativeSource AncestorType={x:Type mah:MetroWindow}}}"
commandparameter="{Binding}">
<Button.Template>
<ControlTemplate>
<Image MaxWidth="100"
Margin="10"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Source="/Resources/activateDevice.png" />
</ControlTemplate>
</Button.Template>
</Button>
</Binding.TargetNullValue>
</Binding>
</ContentControl.Content>
</ContentControl>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
TargetNullValue
中定义的“激活设备”按钮仅针对列表中的最后一项显示。其他项目仅显示为空白,对于没有数据模板的视图模型,甚至没有默认的“ Some.Namespace.SomeViewModel”文本。放到Devices
集合中的内容并不重要,我总是只看到最右边(即最后一个)项目上的按钮。
我不知道为什么?
编辑:TargetNullValue
似乎只创建了一次,然后为每个项目“重用”,因此它是从上一个项目“窃取”的。如果是这样,我该如何预防?我希望为每个项目创建按钮的新实例。
编辑:@KeithStein解决方案有效:
<ItemsControl Grid.Row="1" ItemsSource="{Binding Devices}">
<ItemsControl.Resources>
<Button x:Key="activateDeviceButton"
x:Shared="False"
Command="{Binding DataContext.activateCommand,RelativeSource={RelativeSource AncestorType={x:Type mah:MetroWindow}}}"
commandparameter="{Binding Path=DataContext,ElementName=deviceRoot}">
<Button.Template>
<ControlTemplate>
<Image MaxWidth="100"
Margin="10"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Source="/Resources/activateDevice.png" />
</ControlTemplate>
</Button.Template>
</Button>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<itemspaneltemplate>
<UniformGrid Rows="1" />
</itemspaneltemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type viewModels:IDeviceViewModel}">
<Grid x:Name="deviceRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}"
Grid.Row="0"
Margin="5"
HorizontalAlignment="Center" />
<ContentControl Grid.Row="1" Content="{Binding CurrentState,TargetNullValue={StaticResource activateDeviceButton}}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
现在的问题是:为什么TargetNullValue
首先被共享?