如何将 xaml 标记文件中的参数传递给 UserControl 构造函数?

How can I pass a parameter from the xaml markup file to the UserControl constructor?

我有一个 StepsWnd window,其中 UserControl StepProp 使用了两次,在单独的文件中声明。

 <Window x:Class="MyProject.StepsWnd"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:c1="http://schemas.componentone.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyProject"
    Height="550" Width="850">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <local:StepProp Grid.Column="0" DataContext="{Binding Path=PrevStepVM}" x:Name="m_PrevStep"/>
        <local:StepProp Grid.Column="1" DataContext="{Binding Path=CurStepVM}" x:Name="m_CurStep"/>
    </Grid>
</Window>

创建 StepsWnd window 时,将调用 StepProp 构造函数两次 - m_PrevStep 和 m_CurStep。

public class StepProp : UserControl
{
    public StepProp()
    {
        InitializeComponent();
    }
    //...
}

如何从 StepsWnd window 的标记中将参数传递给 StepProp class 构造函数,以便我可以识别谁在调用构造函数,m_PrevStep 或 m_CurStep?要得到这样的东西?

public class StepProp : UserControl
{
    public StepProp(object parameter)
    {
        InitializeComponent();
        if ((string)parameter == "PrevStep")
        {
            //todo somthing
        }
        else if ((string)Param == "CurStep")
        {
            //todo somthing else
        }
    }
    //...
}

How can I pass a parameter to the StepProp class constructor from the markup of the StepsWnd window, so that I can identify who is calling the constructor, m_PrevStep or m_CurStep?

你不能。 XAML 是一种 标记 语言,您不能使用除不接受任何参数的默认构造函数之外的任何其他构造函数来创建 UserControl 的实例。所以忘记在 XAML.

中使用依赖注入

如果您希望构造函数根据您正在创建的实例表现不同,您可能应该考虑创建两种不同的 UserControl 类型,例如它们可能共享相同的基础 class 或继承自彼此。

或者,您可以按照评论中的建议定义和设置 属性:

<local:StepProp x:Name="m_PrevStep" YourProperty="m_PrevStep" />

...并处理 setter 或 属性 中的任何逻辑(如果您正在定义依赖项 属性,则处理回调)。

请注意,属性 值在构造函数中不可用,因为必须在 XAML 处理器实际设置 属性.[=14 之前创建实例=]