簡體   English   中英

如何將參數傳遞給DataContext?

[英]How to Pass a Parameter to a DataContext?

是否可以通過XAML將某些數據傳遞到綁定源/數據上下文?

在我的特定情況下,我希望為綁定源提供對創建它的窗口的引用。

例如:

<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是我自己創建的,因此,如果這涉及添加構造函數參數或其他內容,那會很好!

更新:我想要一個符合我項目特定要求的解決方案:

  • 不使用x:Reference擴展名。
  • 在后面使用盡可能少的代碼(我希望能夠在XAML中完成大部分工作)。

謝謝!

我有兩種方法可以想到,一種是在MarginDataContext構造函數中使用一個參數,另一種是在后面的代碼中使用DataContextChanged。

方法1:參數化的MarginDataContext有關更多信息,請參見MSDN上的x:Arguments指令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;
        }
    }
}

您可以在XAML中訪問MarginDataContext的任何屬性。 假設您創建了一個WindowInstance屬性,然后可以使用x:Reference在MarginDataContext的構造上簡單地分配它:

<local:MarginDataContext x:Key="MyDC" WindowInstance="{x:Reference MyWindow}"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM