摘要:使用'RelativeSource FindAncestor' 無法找到對應的ViewModel
狀況說明:
父控件=>ItemSource(資料來源)=>子模板(ItemTemplate) 無法找到要參考的最上層的ViewModel資訊
當在操作子模板資料時,需要參考到父控件資料屬性(父類的ViewModel)。
說明:
設置一使用者控建,並給予依賴屬性(設定為object),將其放置於 Resources,綁定Data="{Binding}"會自動綁定最近的DataContext。如此一來就可以參考到此Xaml頁面的ViewModel
<UserControl.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}" /></UserControl.Resources>
<DataGridTemplateColumn Visibility="{Binding Data.IsVisible,
Source={StaticResource proxy},
Converter={StaticResource BooleanToVisibilityConverter}}">
And the binding proxy.
public class BindingProxy : Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object),
typeof(BindingProxy), new UIPropertyMetadata(null));
}