我在更新 Xamarin UWP 應用中的影像時遇到問題。首先,我想說我在這個問題上看到了多個其他執行緒,但是沒有一個能夠解決我的困境,而且很多都非常過時。
這是我的場景:我正在使用三個影像,分別命名為 green.png、red.png 和 gray.png。我在我的 Xamarin 應用程式中顯示一個影像,并且根據關聯的 .cs 檔案中呼叫的特定浮點數,我想將影像更改為另一種顏色。因此,例如,如果浮點數低于 15,我希望影像是紅色的。
以下是我目前在不使用更改代碼的情況下顯示我的影像的方式,即此代碼作業正常并且我的影像出現在應用程式中:
<Image Source="{pages:ImageResource BLE.Client.Pages.red.png}" Opacity="0.6"/>
它們當前存盤在與 XAML 檔案本身相同的目錄中。我知道在 Android 上有一個Resources檔案夾,但我沒有看到 UWP 的任何等價物,所以我以這種方式加載我的影像。
根據我在這里看到的另一篇文章,我嘗試這樣做的一種方法是:
<Image Source="{Binding HeadColor, StringFormat='pages:ImageResource BLE.Client.Pages.\{0\}.png', Mode=TwoWay}" Opacity="0.6"/>
這應該起作用的方式取決于我的浮點值,我在 .cs 檔案中使用字串 HeadColor 并對其執行 OnPropertyChanged。它總是包含字串“green”、“red”或“gray”,并且使用這種方法,它應該將自己插入到影像位置字串中。但是,這不起作用。
作為參考,以下是我在 .cs 檔案中更新 HeadColor 字串的方法:
private string _HeadColor;
public string HeadColor {get => _HeadColor; set {_HeadColor = value; OnPropertyChanged("HeadColor");}}
...
if (SensorAvgValue > 15) {_HeadColor = "green";}
else {_HeadColor = "red";}
RaisePropertyChanged(() => HeadColor);
我也嘗試過使用 IValueConverter,但這也不起作用。
因此,總而言之,我的問題是如何最好地動態更改我想使用的影像。它們都是相同的尺寸和相同的目錄,唯一的區別是它們的名稱“green.png”、“red.png”和“gray.png”。有沒有更好的方法來呼叫/加載影像?
謝謝!
uj5u.com熱心網友回復:
這在 iOS 上適用于我 - 我沒有要測驗的 UWP 環境,但它應該可以正常作業。我的 iOS 資源中有兩個影像“reddot.png”和“greendot.png”
<StackLayout Padding="20,50,20,50">
<Image Source="{Binding HeadColor, StringFormat='\{0\}dot.png'}" Opacity="0.6"/>
<Button Clicked="ChangeColor" Text="Click!!" />
</StackLayout>
代碼隱藏
public partial class MainPage : ContentPage, INotifyPropertyChanged
{
private string headColor = "red";
public string HeadColor
{
get
{
return headColor;
}
set
{
headColor = value;
OnPropertyChanged();
}
}
public MainPage()
{
InitializeComponent();
this.BindingContext = this;
}
protected void ChangeColor(object sender, EventArgs args)
{
if (HeadColor == "red")
{
HeadColor = "green";
}
else
{
HeadColor = "red";
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/459765.html
標籤:xamarin xamarin.forms uwp uwp-xml xamarin.uwp
上一篇:XamarinFormsAndroid-如何在VisualStudioforMac2019中啟用ProguardShrinker
