【发布时间】:2013-10-24 10:29:56
【问题描述】:
假设在 xaml 窗口中我有 <UserControl x:Name="Test">...
我有一个自定义MyListBoxItem,只添加了一个依赖属性UserControlProperty,typeof UserControl。
我想使用语法<c:MyListBoxItem UserControl="Test">Information</c:MyListBoxItem>,但我不确定如何将字符串“Test”或“local:Test”的类型转换器写入该 xaml 页面上的 usercontrol Test。
回答“nit”的评论:
<Window.Resources>
<UserControl x:Key="Test" x:Name="Test"
x:Shared="False">
<Button Height="50"
Width="50" />
</UserControl>
</Window.Resources>
与<c:MyListBoxItem UserControl="{StaticResource Test}">Information</c:MyListBoxItem> 一起工作。
但是我想要常规 xaml 定义中的 UserControl 并找到了另外两种方法:
<c:MyListBoxItem UserControl="{x:Reference Test}">
但是x:Reference 给出了编译时错误:方法/操作未实现。它仍然运行,顺便说一句,imo 很奇怪。并且:
<c:MyListBoxItem UserControl="{Binding ElementName=Test}"
这是一个很好的解决方案。
至于你可以通过这个实现什么:
private void Menu_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in e.RemovedItems)
{
// collapse usercontrol
UserControl uc = (item as MyListBoxItem).UserControl;
if (uc != null) uc.Visibility = Visibility.Collapsed;
}
foreach (var item in e.AddedItems)
{
// uncollapse usercontrol
UserControl uc = (item as MyListBoxItem).UserControl;
if (uc != null) uc.Visibility = Visibility.Visible;
}
}
这是支持这种菜单结构的好方法,xaml 定义也很明确:
<c:MyListBoxItem UserControl="{Binding ElementName=Information}" IsSelected="True">Information</c:MyListBoxItem>
<c:MyListBoxItem UserControl="{Binding ElementName=Edit}" IsSelected="False">Edit</c:MyListBoxItem>
<Grid>
<UserControl x:Name="Information" Visibility="Visible"><Button Content="Placeholder for usercontrol Information" /></UserControl>
<UserControl x:Name="Edit" Visibility="Collapsed"> <Button Content="Placeholder for usercontrol Edit" /></UserControl>
【问题讨论】:
标签: c# wpf xaml type-conversion typeconverter