這應該工作。這個想法是你有這個附加的屬性,你將附加到DataGrid
。在附加它的xaml中,您將它綁定到您的ViewModel
上的一個屬性。無論何時您想以編程方式爲SelectedItem
賦值,您還要爲此屬性設置一個值,該屬性將綁定到該屬性。
我已將附加屬性類型設置爲SelectedItem
類型,但老實說,只要您將其設置爲與以前不同的類型,什麼類型都無關緊要。這個附加屬性只是作爲一種手段,以MVVM友好的方式在視圖控件上執行一些代碼(在本例中爲DataGrid
)。
所以,這麼說,這裏的附加屬性代碼:
namespace MyAttachedProperties
{
public class SelectingItemAttachedProperty
{
public static readonly DependencyProperty SelectingItemProperty = DependencyProperty.RegisterAttached(
"SelectingItem",
typeof(MySelectionType),
typeof(SelectingItemAttachedProperty),
new PropertyMetadata(default(MySelectionType), OnSelectingItemChanged));
public static MySelectionType GetSelectingItem(DependencyObject target)
{
return (MySelectionType)target.GetValue(SelectingItemProperty);
}
public static void SetSelectingItem(DependencyObject target, MySelectionType value)
{
target.SetValue(SelectingItemProperty, value);
}
static void OnSelectingItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var grid = sender as DataGrid;
if (grid == null || grid.SelectedItem == null)
return;
// Works with .Net 4.5
grid.Dispatcher.InvokeAsync(() =>
{
grid.UpdateLayout();
grid.ScrollIntoView(grid.SelectedItem, null);
});
// Works with .Net 4.0
grid.Dispatcher.BeginInvoke((Action)(() =>
{
grid.UpdateLayout();
grid.ScrollIntoView(grid.SelectedItem, null);
}));
}
}
}
而這裏的XAML片段:
<Window ...
xmlns:attachedProperties="clr-namespace:MyAttachedProperties">
...
<DataGrid
attachedProperties:SelectingItemAttachedProperty.SelectingItem="{Binding MyViewModel.SelectingItem}">
...
</DataGrid>
</Grid>
嘗試實施「行爲」時會出現什麼錯誤? – Gjeltema
@Gjeltema'無法找到類型或命名空間名'行爲'(您是否缺少使用指令或程序集引用?)' – Andy
您是否在項目中引用了System.Windows.Interactivity.dll? – Gjeltema