我想我知道你想做什么。这里有一个可能的解决方案。
为了使用SelectedItem属性,应该使用列表框(或从选择器控件派生的任何内容)。
<UserControl>
<Grid>
<StackPanel Grid.Column="0">
<ListBox x:Name="SettingListBox" Template="{StaticResource myDataTemplate}">
<Item>
<Setting Title="Foo" Description="Bar">
<Option>Yes</Option><Option>No</Option>
</Setting>
</Item>
</ListBox >
</StackPanel>
<StackPanel Grid.Column="1">
<TextBlock x:Name="Description"
Text="{Binding SelectedItem.Description, ElementName=SettingListBox}"/>
</StackPanel>
</Grid>
</UserControl>
为了解决当您打开组合框下拉菜单时,列表框不关注项目的问题,我有一个附加属性可以为您解决这个问题。
public class ListBoxHelper
{
#region Dependency Property
public static bool GetCanFocusParent(DependencyObject obj)
{
return (bool)obj.GetValue(CanFocusParentProperty);
}
public static void SetCanFocusParent(DependencyObject obj, bool value)
{
obj.SetValue(CanFocusParentProperty, value);
}
// Using a DependencyProperty as the backing store for CanFocusParent. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CanFocusParentProperty =
DependencyProperty.RegisterAttached("CanFocusParent", typeof(bool), typeof(ListBoxHelper), new UIPropertyMetadata(false, OnCanFocusParentChanged));
#endregion
private static void OnCanFocusParentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var element = obj as UIElement;
if(element == null) return;
if((bool)args.NewValue)
element.PreviewMouseDown += FocusOnParent;
else
element.PreviewMouseDown -= FocusOnParent;
}
private static void FocusOnParent(object sender, RoutedEventArgs e)
{
var listBoxItem = VisualUpwardSearch<ListBoxItem>(sender as DependencyObject) as ListBoxItem;
if (listBoxItem != null) listBoxItem.IsSelected = true;
}
public static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
{
while (source != null && source.GetType() != typeof(T))
source = VisualTreeHelper.GetParent(source);
return source;
}
}
这个小类所做的是帮助控件在激活列表框中的控件(即组合框)时聚焦于所选的列表框项。当在列表框项中单击鼠标时,它会工作。
现在你要做的就是像这样把它连接到你的组合框上:
<DataTemplate x:Key="myDataTemplate">
<ComboBox
TitleText="{Binding Title}"
DescriptionText="{Binding DescriptionText}"
CotrolHelper:ListBoxHelper.CanFocusParent="true"/>
</DataTemplate>
其中controlHelper是:
xmlns:ControlHelper="clr-namespace:WhereYouPutYour.ListBoxHelperClass"
最后,要禁用滚动条(但我建议将其设置为自动),可以使用列表框中的ScrollViewer附加属性,如下所示:
<ListBox
x:Name="SettingListBox"
Template="{StaticResource myDataTemplate}"
ScrollViewer.VerticalScrollBarVisibility="Disabled" >
<Item>
<Setting Title="Foo" Description="Bar">
<Option>Yes</Option><Option>No</Option>
</Setting>
</Item>
</ListBox >