我有一个自定义的ItemsControl,它(2路)绑定到ObservableCollection。每行有1个TextBox和2个按钮, - 按钮将删除当前行,+按钮将插入一个新行,如下所示:
我的数据实体定义:
namespace SilverlightApplication1
{
using System.Collections.ObjectModel;
public class DeviceInfo
{
public DeviceInfo(string remarks)
{
this.Remarks = remarks;
}
public string Remarks { get; set; }
}
public class MainPageViewModel
{
public MainPageViewModel()
{
}
private ObservableCollection<DeviceInfo> devices = new ObservableCollection<DeviceInfo>();
public ObservableCollection<DeviceInfo> Devices
{
get
{
return this.devices;
}
set
{
this.devices = value;
}
}
}
}
这是我的XAML代码:
<Grid x:Name="LayoutRoot" Background="White">
<sdk:HeaderedItemsControl ItemsSource="{Binding Devices, Mode=TwoWay}" Margin="5, 5, 5, 5">
<sdk:HeaderedItemsControl.Template>
<ControlTemplate TargetType="sdk:HeaderedItemsControl">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*" />
<ColumnDefinition Width="5*" />
<ColumnDefinition Width="5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="4*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Margin="0, 0, 5, 10" HorizontalAlignment="Left" Text="Remarks"/>
<Grid Grid.Row="1" Grid.ColumnSpan="4" Width="Auto" Height="Auto" Background="White">
<ItemsPresenter/>
</Grid>
</Grid>
</ControlTemplate>
</sdk:HeaderedItemsControl.Template>
<sdk:HeaderedItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</sdk:HeaderedItemsControl.ItemsPanel>
<sdk:HeaderedItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*"/>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding Path=Remarks}" Margin ="0, 0, 10, 10"></TextBox>
<Button x:Name="Delete" Grid.Column="1" Margin="0, 0, 5, 10" Click="Delete_Click" Visibility="{Binding Path=Devices, Mode=TwoWay, Converter={StaticResource collectionElementCountToVisibilityConverter}}">-</Button>
<Button x:Name="Add" Grid.Column="2" Margin="0, 0, 5, 10" Click="Add_Click">+</Button>
</Grid>
</DataTemplate>
</sdk:HeaderedItemsControl.ItemTemplate>
</sdk:HeaderedItemsControl>
我有两个问题:
当用户点击 - 或+时,我想知道选择了哪个DeviceInfo元素,所以我可以删除该元素,或者在其后插入一个新元素,如何在按钮点击事件处理程序中获取该元素?
您可能会注意到,当集合中只有1个元素时, - 按钮是不可见的。我尝试将 - 按钮的Visibility属性绑定到ItemsSource集合,并在集合的计数为1时返回Visibility.Collapse,但绑定没有工作,转换器从未被调用,我该怎么做让它有用吗?
提前致谢!
答案 0 :(得分:0)
对于第一个问题(因为您已经解决了第二个问题),您可以从按钮DeviceInfo
中选择DataContext
,例如:
void Add_Click(object sender, RoutedEventArgs e)
{
DeviceInfo selectedDeviceInfo = (DeviceInfo)((Button)sender).DataContext;
}