Theo bài viết Dự án mã đã đề cập, đây là ví dụ về Mã cho thấy cách thiết lập Hành vi và cách tích hợp Hành vi trong XAML.
cài đặt hành vi:
/// <summary>
/// Exposes attached behaviors that can be
/// applied to TreeViewItem objects.
/// </summary>
public static class TreeViewItemBehavior
{
#region IsBroughtIntoViewWhenSelected
public static bool GetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem)
{
return (bool)treeViewItem.GetValue(IsBroughtIntoViewWhenSelectedProperty);
}
public static void SetIsBroughtIntoViewWhenSelected( TreeViewItem treeViewItem, bool value)
{
treeViewItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);
}
public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =
DependencyProperty.RegisterAttached(
"IsBroughtIntoViewWhenSelected",
typeof(bool),
typeof(TreeViewItemBehavior),
new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged));
static void OnIsBroughtIntoViewWhenSelectedChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
TreeViewItem item = depObj as TreeViewItem;
if (item == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool)e.NewValue)
item.Selected += OnTreeViewItemSelected;
else
item.Selected -= OnTreeViewItemSelected;
}
static void OnTreeViewItemSelected(object sender, RoutedEventArgs e)
{
// Only react to the Selected event raised by the TreeViewItem
// whose IsSelected property was modified. Ignore all ancestors
// who are merely reporting that a descendant's Selected fired.
if (!Object.ReferenceEquals(sender, e.OriginalSource))
return;
TreeViewItem item = e.OriginalSource as TreeViewItem;
if (item != null)
item.BringIntoView();
}
#endregion // IsBroughtIntoViewWhenSelected
}
Sau đó tích hợp các TreeViewItemBehavior trong XAML:
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="local:TreeViewItemBehavior.IsBroughtIntoViewWhenSelected" Value="True"/>
</Style>
</TreeView.ItemContainerStyle>
Hãy vui vẻ :-)
Tôi nghĩ MVVM nên dừng lại ở khái niệm "lựa chọn". Nếu điều đó không di chuyển mục vào chế độ xem, tôi sẽ sử dụng các sự kiện thông thường trong Chế độ xem. –
Bạn nói đúng, chế độ xem không nên quan tâm đến chế độ xem. Nhưng đây là một số trường hợp đặc biệt mà là "ở biên giới" của MVVM tôi tin. –
Máy ảo sẽ chỉ ra một mục nhất định, nhưng đó là nó. Các vấn đề cuộn được xử lý tốt hơn trong Chế độ xem. –