【问题标题】:WPF when I change the string to which binded Text of TextBlock, the text doesn't change [duplicate]WPF当我更改TextBlock的绑定文本的字符串时,文本不会改变[重复]
【发布时间】:2022-01-12 21:39:36
【问题描述】:

我在 ListBox 中有一个 ItemTemplate,其中包含 Image(国家标志)和 TextBlock(国家名称)

列表框:

<ListBox x:Name="countriesList" Background="#a79473" Foreground="#e6d9c4">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Height="40" Background="#a79473">
                <Image Source="{Binding Flag.Source}"/>
                <TextBlock Text="{Binding Name}" Foreground="#e6d9c4" FontSize="20"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

国家级:

public class Country
{
    public string Name { get; set; }
    public Image Flag { get; set; }
    
    public Country()
    {
        Flag = new Image();
    }
}

当国家改变国旗时,一切正常,但当名称改变时,没有任何反应,
我想当我更改名称时,绑定仍然绑定到旧名称,但是如何处理呢?

Country country = new Country();
countriesList.Items.Add(country);
country.Name = "test";
country.Flag.Source = flagImage.Source;

附注这是我关于stackoverflow的第一个问题,我希望我在任何地方都没有犯错:)

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您的Country 类应实现INotifyPropertyChanged 并在Name 属性设置为新值时引发PropertyChanged 事件:

    public class Country : INotifyPropertyChanged
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; RaisePropertyChanged(); }
        }
    
        public Image Flag { get; set; }
    
        public Country()
        {
            Flag = new Image();
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged([CallerMemberName]string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    设置Source 属性按原样工作的原因是因为它是一个依赖属性。附带说明一下,Country 之类的模型不应包含Image 之类的 UI 元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 2011-03-09
      相关资源
      最近更新 更多