我有 2 個用戶控制元件視圖,它們是:Bmw.xaml和Audi.xaml.
在兩個 xamls 中,我都添加了以下內容:
<UserControl x:Class=TestProject.Views.Fragments.Audi
<!--The standard code generated by visual studio-->
xmlns:viewModels="clr-namespace:TestProject.ViewModels"
<Grid>
<!--XAML CODE-->
</Grid>
</UserControl>
在 bmw.caml.cs 和 audi.xaml.cs 中,我的建構式中有這個:
public Audi()
{
InitializeComponent();
this.DataContext = new BrandViewModel();
}
和
public BMW()
{
InitializeComponent();
this.DataContext = new BrandViewModel();
}
在 ViewModel 中是我的函式,為了簡單起見,當奧迪呼叫 ViewModel 時,我想呼叫函式 ActionAudi(),而當寶馬呼叫它時,我想呼叫 ActionBMW()。
有沒有什么好辦法可以在viewModel類中知道是屬于audi還是bmw usercontrol?因為根據這一點,必須執行不同的邏輯。
先感謝您!
uj5u.com熱心網友回復:
首先,創建一個列舉來定義您擁有哪個品牌。像這樣
public enum Brands
{
Audi,
BMV,
Vinfast
}
其次,將您的 ViewModel 的建構式修改為這樣的想法。
public BrandViewModel(Brands brand)
{
// passing brand to a field or property
}
最后,通過您剛剛創建的新建構式設定您的 DataContext。
public Audi()
{
InitializeComponent();
this.DataContext = new BrandViewModel(Brands.Audi);
}
和
public BMW()
{
InitializeComponent();
this.DataContext = new BrandViewModel(Brands.BMW);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/393094.html
