前言
作為一個(gè)使用Vue非常熟練的C#全干工程師。當(dāng)我在接觸WPF的時(shí)候,我就一直想用Vue的想法去重寫WPF框架。經(jīng)過(guò)一個(gè)星期的琢磨,終于琢磨出來(lái)了如何優(yōu)雅的入?yún)ⅰF陂g看了上百篇博客,瀏覽了一堆的視頻教程。
代碼
用戶控件的cs
TestController.xaml
public partial class TestControl : UserControl
{
/// <summary>
/// 聲明數(shù)據(jù)源
/// </summary>
public TestControllerViewModel testControl = new TestControllerViewModel();
/// <summary>
/// 用于靜態(tài)編譯通過(guò),根據(jù)我兩天的試驗(yàn),這個(gè)值是不會(huì)觸發(fā)get和set指令的,就是個(gè)花瓶。
/// </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) =>
{
//使用回調(diào)函數(shù)去重新設(shè)置數(shù)據(jù)源
var model = (TestControl)item;
model.testControl.TestTitle = res.NewValue as string;
})));
public TestControl()
{
InitializeComponent();
//必須要這么寫,不然Bind賦值傳不進(jìn)去
( this.Content as FrameworkElement ).DataContext = testControl;
}
}
TestController.xaml.cs
用戶控件的xaml
<Grid Background="White">
<StackPanel>
<TextBlock Text="{Binding TestTitle}" FontSize="50"/>
<!--<Button Content="按鈕" FontSize="50" />-->
</StackPanel>
</Grid>
TestControllerViewModel,數(shù)據(jù)源
public class TestControllerViewModel
{
public string TestTitle { get; set; }
public TestControllerViewModel()
{
TestTitle = "我是初始值";
}
}
主窗口
<Grid>
<StackPanel>
<!--這里面?zhèn)鞯氖?我是Bind賦值"-->
<Views:TestControl TestTitle="{Binding TestTitle}" />
<Views:TestControl TestTitle="我是直接賦值" />
<Views:TestControl />
</StackPanel>
</Grid>
實(shí)現(xiàn)效果
代碼邏輯
總結(jié)
期間遇到許多困難,WPF國(guó)內(nèi)相關(guān)資料極少,英語(yǔ)也不知道怎么提問(wèn),GPT也沒(méi)有給我想要的答案,難得我都要放棄了。因?yàn)槲乙恢毕胂馰ue那樣優(yōu)雅的入?yún)?,按照Vue的一切都是組件的想法去開(kāi)發(fā),因?yàn)檫@樣極大的減少了開(kāi)發(fā)的難度,降低了耦合,提高了組件的復(fù)用。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-607812.html
幸好我成功了,所有的努力沒(méi)有白費(fèi)。只要我能Bind入?yún)ⅲ揖湍馨凑誚ue的邏輯重構(gòu)WPF頁(yè)面的開(kāi)發(fā)。我相信我有這個(gè)能力。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-607812.html
到了這里,關(guān)于按照Vue寫WPF(1):屬性綁定的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!