WPF XAML 中参数化构造函数赋值 DataContext
引入命名空间:
xmlns:system="clr-namespace:System;assembly=mscorlib"
XAML:
<Window x:Class="WpfApp.MainWindow"
        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:system="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="600">
    <Window.DataContext>
        <ObjectDataProvider ObjectType="local:Welcom">
            <ObjectDataProvider.ConstructorParameters>
                <system:String>孙悟空</system:String>
                <system:Int32>100</system:Int32>
            </ObjectDataProvider.ConstructorParameters>
        </ObjectDataProvider>
    </Window.DataContext>
    <Grid>
        <TextBox Height="20" Width="200" BorderBrush="Black" Text="{Binding Name}"/>
    </Grid>
</Window>
CS:
public class Welcom : ObservableObject
{
    private string _name = "Hello World!!!";
    public string Name
    {
        get => _name;
        set { _name = value; RaisePropertyChanged(nameof(Name)); }
    }
    public Welcom(string name, int score)
    {
        _name = name + " " + score.ToString() + " 分";
    }
}
视图:

<Window.DataContext>
    <ObjectDataProvider ObjectType="local:MainVM">
        <ObjectDataProvider.ConstructorParameters>
            <sys:String>Good</sys:String>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
</Window.DataContext>
Code behind 转化 DateContext:
ObjectDataProvider odp = DataContext as ObjectDataProvider;
m_MainVM = odp.ObjectInstance as MainVM;
如何在 XAML 代码中传入 this 对象参数,现在还不知道;还是在 behind code 里面处理吧。
How do you pass "this" to the constructor for ObjectDataProvider in XAML?
 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号