WPF 用户控件依赖注入赋值

前言

我一直想组件化得去开发WPF,因为我觉得将复杂问题简单化是最好的

如何组件化开发

WPF 用户控件依赖注入赋值_第1张图片

主窗口引用

<Window x:Class="WpfApp1.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:local="clr-namespace:WpfApp1"
        xmlns:MD="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:Views="clr-namespace:WpfApp1.Views"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" >
    <Window.Resources>
        <Style x:Key="my_text" TargetType="TextBlock">
            "FontSize" Value="30" />
            "Margin" Value="8" />
        Style>
    Window.Resources>
    <Window.DataContext >
        
        <local:MainWindowViewModel x:Name="viewModel"/>
    Window.DataContext>
    <Grid>
        
        <Views:ViewA Margin="10"
                Title="{Binding ElementName=viewModel,Path=TitleValue}" />
    Grid>
Window>

cs部分

namespace WpfApp1
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MainWindowViewModel
    {
        public string TitleValue { get; set; } =  "我是测试数据";

    }
}

控件窗口

    <UserControl.DataContext>
        <local:ViewAViewModel />
    UserControl.DataContext>

    <Grid>
        <TextBlock Text="{Binding Title}" />
    Grid>
/// 
/// ViewA.xaml 的交互逻辑
/// 
public partial class ViewA : UserControl
{

    public static readonly DependencyProperty TitleProperty;

    /// 
    /// 为了拿到数据源需要定义一下
    /// 
    private ViewAViewModel ViewModel = new ViewAViewModel();
    public ViewA()
    {
        InitializeComponent();
        ViewModel = (ViewAViewModel)DataContext;

    }
    static ViewA()
    {
        //静态构造
        TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ViewA),new PropertyMetadata("",
            new PropertyChangedCallback((item, res) =>
            {
                //拿到数据,再次赋值
                var model =(ViewA)item;
                model.ViewModel.Title = (string)res.NewValue;
            })));
    }

    /// 
    /// 只是为了有代码提示,添加依赖属性后不会被调用
    /// 

    public string Title { get; set; }




}
public partial class ViewAViewModel : ObservableObject
{
    /// 
    /// 通知更新
    /// 
    [ObservableProperty]
    private string title = "ViewA Title!";

}

你可能感兴趣的:(WPF,入门知识,wpf)