該型別的Text-propertyEditor使用意想不到的方式來表示換行符。例如,在 Windows 上的 UWP 中,它使用 \r 而不是 \r\n 如Environment.NewLine屬性所宣傳的那樣。這似乎是一些特定于平臺的行為(但是我希望 Windows 上的 UWP \r\n)。
網路顯示了有關此問題的一些資訊,但當前版本中似乎沒有解決方案:https : //github.com/xamarin/Xamarin.Forms/pull/6823 https://github.com/xamarin/Xamarin .Forms/issues/3020
我真的很想規避這種行為,這樣我就不必對我的視圖模型處理進行一些黑客攻擊。
我試圖創建一個IValueConverter我在 Binding 中使用的并替換虛假的換行符。這作業正常,但是會在編輯器中帶來可用性問題(游標定位開始出錯)。如果我可以設定 UpdateSourceTrigger,這會起作用,但是 Xamarin 似乎不支持。
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
if(value is string sv) {
if(sv.IndexOf("\r") > -1 && sv.IndexOf("\n") < 0) {
return sv.Replace("\r",Environment.NewLine);
}
}
return value;
}
我嘗試的另一件事是,將處理程式添加到Editor.Completed. 這樣做的問題是,系結在事件之后執行,因此我的更改被撤消。
private void TextContent_Completed(object sender, EventArgs e) {
var vm= ...
vm.TextContent= XamarinNewlineRestorer.TransformToClrSpecific(vm.TextContent);
}
有誰知道這個問題的解決方案?還是我誤解了大事?
uj5u.com熱心網友回復:
解決方法是setter method在 viewmodel 中定義的屬性中進行替換,然后將其系結到 Editor 。
就像是
public string WorkAroundContent
{
get {
switch (Device.RuntimePlatform)
{
case Device.UWP:
return _Content.Replace("\n", "\r");
default:
return _Content;
}
}
set
{
string newContent;
switch (Device.RuntimePlatform)
{
case Device.UWP:
newContent = value.Replace("\r", "\n");
break;
default:
newContent = value;
break;
}
if (_Content == newContent) return;
Content = newContent;
}
}
請參閱 https://github.com/xamarin/Xamarin.Forms/issues/3020#issuecomment-507332809。
uj5u.com熱心網友回復:
正如我在帖子中所說,我不喜歡污染我的視圖模型的想法。然而,ColeX 的回答向我展示了我的錯誤之處。
最終的解決方案是創建一個帶有加法的值轉換器,它可以在兩個方向上更改資料。這是我第一次嘗試時出現的錯誤,導致 Xamarin 編輯器組件失速。對于誰對基于值轉換器的解決方案感興趣的解決方案,我認為這是可取的:
public class XamarinWorkaroundNewlineValueConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is string stringValue && targetType == typeof(string)) {
switch (Device.RuntimePlatform) {
case Device.UWP:
return stringValue.Replace(Environment.NewLine, "\r");
default:
return stringValue;
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
if(value is string stringValue && targetType==typeof(string)) {
switch (Device.RuntimePlatform) {
case Device.UWP:
return stringValue.Replace("\r", Environment.NewLine);
default:
return stringValue;
}
}
return value;
}
}
在 App.xaml 或視圖的資源部分宣告轉換器:
<[your value converter namespace]:XamarinWorkaroundNewlineValueConverter x:Key="XamarinWorkaroundNewlineValueConverter"/>
在視圖中像這樣使用它:
<Editor Text ="{Binding [YourTextPropertyName],Converter={StaticResource XamarinWorkaroundNewlineValueConverter}}" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/313168.html
標籤:沙马林 xamarin.forms xamarin.forms.editor
