![](/img/trans.png)
[英]How to set BindingContext of multiple pages to the same ViewModel in Xamarin.Forms?
[英]Xamarin.Forms - Variable on multiple pages
我正在開發一個帶有 BLE 實現的 Xamarin.Forms 應用程序。 在應用程序中,我想創建一個具有彈出結構的應用程序。 然而,為此,應用程序的多個頁面需要一些變量/數據。 僅 C# 實施需要數據,XAML 實施不需要數據。 在類/頁面中,變量和數據的傳輸效果很好。 但是,不是在訪問另一個頁面時。
我已經嘗試過全局函數、getter 和 setter 以及委托,但還沒有找到解決問題的方法。
你們中有人對此有想法甚至解決方案嗎? 謝謝
委托全局函數(非私有)getter 和 setter 函數
這里有三種值得了解的“靜態”技術。
1. XAML x:Static
...
xmlns:local="clr-namespace:MyNameSpace"
...
<Label Text="{x:Static local:MyClass.MyGlobalValue}" />
public class MyClass
{
public static string MyGlobalValue;
}
2. StaticResource
靜態資源
<Label BackgroundColor="{StaticResource MyDarkColor}" />
在 App.xaml 中:
<Application ...
<Application.Resources>
<Color x:Key="MyDarkColor">#112233</Color>
...
3. 值為 static 的實例屬性“proxy”。
這個“技巧”通過“實例屬性”訪問“靜態”。 因此,對於其他代碼(和 XAML)而言,它看起來像任何其他屬性。
<Label BackgroundColor="{Binding MyDarkColor}" />
// In the class that `BindingContext` is set to:
public static Color MyGlobalValue;
public Color MyDarkColor => MyGlobalValue;
如果 static 在不同的 class 中:
// In the class that `BindingContext` is set to:
public SomeType MyDarkColor => Class1.MyGlobalValue;
...
public class Class1
{
public static SomeType MyGlobalValue;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.