![](/img/trans.png)
[英]Binding list to textbox won't update if ObservableCollection
[英]Textbox binding won't update on RaisePropertychanged
使用Mvvm庫,UWP,C#。
問題:如果在視圖模型中更改了值並且文本框關注該時刻,則視圖不會更新文本框的內容。 可以更新未獲得焦點的文本框的viewmodel屬性。
清除混淆:文本框 - >有焦點 - >輸入內容 - >傳遞給綁定屬性 - >屬性集,更改值並調用RaisePropertyChange。 - >文本框不會更新。
如果在ViewModel中更改了綁定到不同TextBox的屬性,並且使用該屬性作為目標調用RaisePropertyChanged,則該TextBox會更新。
差異似乎是具有焦點的文本框不會在RaisePropertyChanged上更新。 它確實在wpf中執行此操作。
下面的代碼是一個示例,而不是實際的應用程序。 它確實顯示了問題,並且就像實際的應用程序一樣。 添加連字符以更改輸入。 如果RaisePropertyChanged確實有效,則連字符將顯示在編輯框中,但不會。
我的頁面:
<Page x:Class="BindingTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BindingTest.VML"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding MainViewModel, Source={StaticResource Locator}}" >
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="0,144,0,109">
<TextBox x:Name="textBox1"
Text="{Binding Item1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Margin="10,137,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="340"/>
<TextBox x:Name="textBox2"
Text="{Binding Item2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Margin="10,174,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="340"/>
</Grid>
我的ViewModel:
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace BindingTest
{
public class MainViewModel:ViewModelBase
{
string _item1 = "";
string _item2 = "";
public string Item1 {
get
{
return _item1;
}
set
{
_item1 = value + "-";
RaisePropertyChanged("Item1");
}
}
public string Item2
{
get {
return _item2;
}
set
{
_item2 = value + "-";
RaisePropertyChanged("Item2");
}
}
}
}
如果將文本放入其中一個文本框中,則會調用屬性集,更改值,不在文本框中更新值。
如果我在textbox1的setter中調用textbox2的propertychanged,它將更新:
public string Item1 {
get
{
return _item1;
}
set
{
_item2 = value + "-";
RaisePropertyChanged("Item2");
}
}
就好像具有焦點的文本框只要具有焦點就不會更新它的內容。
嘗試刪除
updateSourceTrigger=PropertyChanged
從您的文本框綁定
on the viewmodel should be enough 上的就足夠了
這是我使用的技巧:
而不是調用RaisePropertyChanged()調用以下方法:
public async void ForceRaisePropertyChanged(string propName)
{
await Task.Delay(1);
RaisePropertyChanged(propName);
}
它就像一個魅力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.