使用样式(MAUI)时,文本属性值在运行时不会更改

问题描述 投票:0回答:1

我使用了标签的样式,并将其文本属性绑定到 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 属性

binding label styles runtime maui
1个回答
0
投票

使用 Viewmodel 中的属性更改其文本后,标签应在视图上呈现,该属性绑定到 Style 中的 Text 属性

无法实时更改

Style
:

<Label ...
       Style="{StaticResource CustomLabelStyle}"
       .../>

直接使用这个可以实时改变标签的文字:

<Label HeightRequest="50"
       Background="red"
       Text="{Binding SelectedItem,Mode=TwoWay}"
       x:Name="label"/>

这是effect

© www.soinside.com 2019 - 2024. All rights reserved.