簡體   English   中英

在隱藏代碼公開的ViewModel上設置子屬性的WPF XAML語法是什么?

[英]What is the WPF XAML syntax to set a subproperty on a ViewModel exposed by the code-behind?

我有一個具有名為“ LoginViewModel”的屬性的用戶控件。 它包含控件綁定到的視圖模型的實例。

LoginViewModel具有一個名為“ UserName”的屬性(該類實現INotifyPropertyChanged)。

當我在另一個頁面上使用用戶控件時,我希望能夠通過XAML在LoginViewModel屬性上設置一些屬性。 我似乎不太願意為此提供正確的語法。 我可以直接在后面的代碼中公開它們,並像這樣設置它們:

<rcs:LoginComponent x:Name="Login" UserName="Test"></rcs:LoginComponent>

但是然后我基本上必須從我的ViewModel復制所有屬性,這很愚蠢。

我試過這種變化:

<rcs:LoginComponent x:Name="Login">
   <rcs:LoginViewModel UserName="Test"></rcs:LoginViewModel>
</rcs:LoginComponent>

但是然后控件不呈現(盡管沒有錯誤)。 我最后得到一個顯示視圖模型名稱空間的控件(例如MyApp.Components.LoginViewModel“)。

這是什么語法?

您應該像這樣在UserControl的DataContext標記中添加LoginViewModel

<rcs:LoginComponent x:Name="Login">
   <rcs:LoginComponent.DataContext>
      <rcs:LoginViewModel UserName="Test"/>
   </rcs:LoginComponent.DataContext>
</rcs:LoginComponent>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM