我使用了标签的样式,并将其文本属性绑定到 ViewModel 中的属性。最初,我使用 ViewModel 中的属性设置标签的文本值。后来,我通过在按钮单击事件中使用 x:name 引用它来更改其文本属性值。案文也相应改变。然后,当我尝试使用另一个按钮单击事件更改 ViewModel 中的绑定属性时,视图上的文本没有更新。
github 示例链接:https://github.com/RiyashameedM/Label_Text_issue
主页.xaml
<ContentPage.BindingContext>
<local:ViewModel x:Name="vm" />
</ContentPage.BindingContext>
<ContentPage.Resources>
<ResourceDictionary>
<Style TargetType="Label"
x:Key="CustomLabelStyle">
<Setter Property="Text"
Value="{Binding SelectedItem,Mode=TwoWay,Source={x:Reference vm}}"></Setter>
</Style>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout x:Name="stack">
<Button Text="set selected Item"
Command="{Binding ListViewSelectionChangedCommand}"
x:Name="btn"
CommandParameter="{x:Reference label}"
HeightRequest="50" />
<Button Text="ChangeBinding"
Clicked="Button_Clicked_1"
x:Name="btn1" />
<Label HeightRequest="50"
Background="red"
Style="{StaticResource CustomLabelStyle}"
x:Name="label" />
</StackLayout>
ViewModel.cs
public class ViewModel : INotifyPropertyChanged
{
private string selectedItem;
public string SelectedItem
{
get { return selectedItem; }
set { selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
}
}
public ICommand ListViewSelectionChangedCommand { get; set; }
public ViewModel()
{
this.SelectedItem = "old value";
ListViewSelectionChangedCommand = new Command(OnSelectionChanged);
}
private void OnSelectionChanged(object obj)
{
this.SelectedItem = "new value";
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
使用 Viewmodel 中的属性更改其文本后,标签应在视图上呈现,该属性绑定到 Style 中的 Text 属性