Skip to main content
 首页 » 编程设计

c#之WPF 绑定(bind)不更新按钮内容

2024年02月20日13bjzhanghao

有人可以告诉我这个源代码有什么问题吗? 当我单击按钮时它没有更新 ist 值? 首先绑定(bind)转换器使他的工作。

源代码非常大,所以我只发布一些片段。

XAML: Instances 是 ObservableCollection 的类型

<ListBox Name="Instances"> 
    <ListBox.ItemTemplate> 
        <DataTemplate> 
            <Button Tag="{Binding Path=Instance.Name}" Content="{Binding Path=Instance.Active, Converter={StaticResource BTSC}}" Click="ChangeAccess"/> 
            <TextBlock Text="{Binding Path=Instance.Name}"/> 
         </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

转换器:

public class BoolToStringConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        if (((Boolean)value) == true) 
            return "No"; 
        else 
            return "Yes"; 
    } 
 
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        throw new NotImplementedException(); 
    } 
}  

事件:

private void ChangeAccess(object sender, RoutedEventArgs e) 
{ 
    for... 
    if ((sender as Button).Tag.ToString() == (DP.Instances[i].Instance as CInstance).Name) 
    { 
        SkipIfAndElse... 
        DP.Instances[i].Instance.Active = true; 
    } 
} 

实例:

class CInstance : INotifyPropertyChanged 
{ 
    private Boolean active; 
    public Boolean Active 
    { 
        get { return active; } 
        set 
        { 
            active = value; 
            NotifyPropertyChanged("Access"); 
        } 
    } 
} 

CInstance 类的所有其他值都按预期更新。

请您参考如下方法:

在你的 CInstance 类中

NotifyPropertyChanged("Access"); 

应该是

NotifyPropertyChanged("Active");