是否可以通过XAML将一些数据传递给绑定源/数据上下文?
在我的特定情况下,我希望为Binding Source提供对创建它的Window的引用。
例如:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyNamespace"
x:Name="MyWindow">
<Window.Resources>
<local:MarginDataContext x:Key="MyDC"/>
</Window.Resources>
<!-- I want to pass in "MyWindow" to "MyDC" here... -->
<Grid Margin="{Binding Source={StaticResource MyDC}, Path=My_Margin}" />
</Window>
注意:MarginDataContext是我自己创建的,所以如果这涉及添加构造函数参数或其他东西,那就可以正常工作了!
更新:我想要一个符合我项目特定要求的解决方案:
谢谢!
答案 0 :(得分:2)
我可以通过两种方式来做到这一点,1)使用MarginDataContext构造函数的参数和2)在后面的代码中使用DataContextChanged。
方法1:参数化MarginDataContext 有关详细信息,请参阅MSDN上的x:Arguments Directive和x:Reference
public class MarginDataContext
{
public WindowInstance { get; set; }
...
}
<!-- xaml -->
<Window.Resources>
<local:MarginDataContext
x:Key="MyDC"
WindowInstance="{x:Reference MyWindow}" />
<!-- or possibly (not sure about this) -->
<local:MarginDataContext
x:Key="MyDC"
WindowInstance="{Binding ElementName=MyWindow}" />
<!-- or even (again, not sure about this) -->
<local:MarginDataContext
x:Key="MyDC"
WindowInstance="{Binding RelativeSource={RelativeSource Self}}" />
</Window.Resources>
方法2:使用后面的代码。有关详细信息,请参阅DataContextChanged。
public class MyWindow : Window
{
...
public MyWindow()
{
// Attach event handler
this.DataContextChanged += HandleDataContextChanged;
// You may have to directly call the Handler as sometimes
// DataContextChanged isn't raised on new windows, but only
// when the DataContext actually changes.
}
void HandleDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var dc = DataContext as MarginDataContext;
if (dc != null)
{
// Assuming there is a 'MyWindow' property on MarginDataContext
dc.MyWindow = this;
}
}
}
答案 1 :(得分:2)
您可以在XAML中访问MarginDataContext的任何属性。因此,假设您创建了一个WindowInstance
属性,然后可以使用x:Reference
在构造MarginDataContext时简单地指定它:
<local:MarginDataContext x:Key="MyDC" WindowInstance="{x:Reference MyWindow}"/>