假設在一個XAML窗口,我有<UserControl x:Name="Test">...
我有一個自定義MyListBoxItem
只有一個的DependencyProperty UserControlProperty
添加的typeof UserControl
。的TypeConverter到用戶控件
我想使用語法<c:MyListBoxItem UserControl="Test">Information</c:MyListBoxItem>
,我不知道如何從字符串「Test」或者「local:Test」向xaml頁面上的usercontrol Test編寫一個typeconverter。
在回答 '尼特' 的評論:
<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的定義,發現這樣做的另外兩種方式:
<c:MyListBoxItem UserControl="{x:Reference Test}">
然而x:Reference
給出了complie時錯誤:未實現的方法/操作。它仍然運行哪個btw很奇怪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>
This Works! usercontrol屬性被設置,這是一件好事。但是我注意到SelectionChanged事件中UserControl的Content和Name屬性是空的? – Gerard
你可以分享如何設置資源中的用戶控件的名稱和內容? – Nitin
對不起,它的工作原理,我忘了給usercontrol的x:Name屬性。查看我的編輯以獲得更好的解決方案。 – Gerard