उल्लिखित कोड प्रोजेक्ट आलेख के अनुसार, यहां कोड उदाहरण है जो दिखाता है कि व्यवहार को कैसे स्थापित किया जाए और XAML में व्यवहार को कैसे एकीकृत किया जाए।
सेटअप व्यवहार:
/// <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
}
फिर XAML में TreeViewItemBehavior एकीकृत:
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="local:TreeViewItemBehavior.IsBroughtIntoViewWhenSelected" Value="True"/>
</Style>
</TreeView.ItemContainerStyle>
है मज़ा :-)
मुझे लगता है कि MVVM "चयनित" की अवधारणा पर बंद कर देना चाहिए। यदि वह आइटम को देखने में स्क्रॉल नहीं करता है, तो मैं दृश्य में नियमित घटनाओं का उपयोग करता हूं। –
आप सही हैं, दृश्यमान को दृश्य के बारे में परवाह नहीं करना चाहिए। लेकिन यहां कुछ विशेष मामला है जो एमवीवीएम के "सीमाओं पर" है, मेरा मानना है। –
वीएम को एक निश्चित वस्तु का संकेत देना चाहिए, लेकिन यह है। दृश्य में स्क्रॉलिंग मुद्दों को बेहतर तरीके से निपटाया जाता है। –