Article Directory
foreword
As a C# full-time engineer who is very skilled in using Vue. When I was in contact with WPF, I always wanted to rewrite the WPF framework with the idea of Vue. After a week of pondering, I finally figured out how to participate gracefully. During this period, I read hundreds of blogs and browsed a bunch of video tutorials.
the code
cs TestController.xaml for the user control
public partial class TestControl : UserControl
{
/// <summary>
/// 声明数据源
/// </summary>
public TestControllerViewModel testControl = new TestControllerViewModel();
/// <summary>
/// 用于静态编译通过,根据我两天的试验,这个值是不会触发get和set指令的,就是个花瓶。
/// </summary>
public string TestTitle {
get; set; }
/// <summary>
/// 用于声明依赖属性,不让只让直接传值,不让Bind传值
/// </summary>
public static readonly DependencyProperty TestTitleProperty =
DependencyProperty.Register("TestTitle", typeof(string), typeof(TestControl), new PropertyMetadata("TestTitle",new PropertyChangedCallback((item,res) =>
{
//使用回调函数去重新设置数据源
var model = (TestControl)item;
model.testControl.TestTitle = res.NewValue as string;
})));
public TestControl()
{
InitializeComponent();
//必须要这么写,不然Bind赋值传不进去
( this.Content as FrameworkElement ).DataContext = testControl;
}
}
TestController.xaml.cs
xaml for user control
<Grid Background="White">
<StackPanel>
<TextBlock Text="{Binding TestTitle}" FontSize="50"/>
<!--<Button Content="按钮" FontSize="50" />-->
</StackPanel>
</Grid>
TestControllerViewModel, data source
public class TestControllerViewModel
{
public string TestTitle {
get; set; }
public TestControllerViewModel()
{
TestTitle = "我是初始值";
}
}
Main window
<Grid>
<StackPanel>
<!--这里面传的是"我是Bind赋值"-->
<Views:TestControl TestTitle="{Binding TestTitle}" />
<Views:TestControl TestTitle="我是直接赋值" />
<Views:TestControl />
</StackPanel>
</Grid>
achieve effect
code logic
Summarize
During this period, I encountered many difficulties. There was very little relevant information about WPF in China, I didn’t know how to ask questions in English, and GPT didn’t give me the answer I wanted. It’s hard to give up. Because I have always wanted to enter parameters as elegantly as Vue, and develop according to the idea that everything in Vue is a component, because this greatly reduces the difficulty of development, reduces coupling, and improves the reuse of components.
Fortunately, I succeeded, and all my efforts were not in vain. As long as I can enter parameters in Bind, I can reconstruct the development of WPF pages according to the logic of Vue. I believe I have this ability.