点击列表框项时更新列表框项

本文关键字:列表 更新 | 更新日期: 2023-09-27 17:50:13

我有一个listbox, listboxitems, imagetextblock。列表框有一个自定义类作为数据源。我想要的是当listboxItem被点击。listboxitem中的image发生了变化。

到目前为止我写的是:

我的自定义类:

public class MemberUser 
    {
        [JsonProperty("member_id", NullValueHandling = NullValueHandling.Ignore)]
        public int member_id { get; private set; }
        [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)]
        public String first_name { get; private set; }
        [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)]
        public String last_name { get; private set; }

        public string fullName
        {
            get
            {
                return String.Format("{0} {1}", first_name, last_name);
            }
        }
        public bool selected{get;set;}
        public string selectedImage
        {
            get{
                if (selected)
                {
                    return "/Assets/ic_selected.png";
                }
                else
                {
                    return "/Assets/ic_not_selected.png";
                }
            }
        }
    }

我的代码隐藏文件(只有你需要理解的代码)

 private OrganizationObject community;
        private IEnumerable<MemberUser> memItems;
        private List<MemberUser> notFoundEvents = new List<MemberUser>();
        public EventAdd()
        {
            InitializeComponent();
            BindData();
        }
        private async void BindData()
        {
            try
            {
                memItems = MemberDataSource.memberList;
                if (memItems.Count() == 0)
                {
                    await MemberDataSource.GetLocalMember();
                    memItems = MemberDataSource.memberList;
                }
                inviteList.DataContext = memItems;
              /*  foreach (MemberUser obj in memItems)
                {
                    if (obj.accepted == 1)
                    {
                        inviteList.Items.Add(obj);
                    }
                }*/
            }
            catch (KeyNotFoundException)
            {
                NavigationService.GoBack();
            }
        }
private void Selectionchanged_Eventhandler_of_Listbox(object sender, SelectionChangedEventArgs e)
        {
            MemberUser myobject = (sender as ListBox).SelectedItem as MemberUser;
            if (myobject.selected)
            {
                myobject.selected = false;
            }
            else
            {
                myobject.selected = true;
            }
        }
我XAML

  <ListBox x:Name="inviteList" ItemsSource="{Binding}" Margin="20,0,0,0" SelectionChanged="Selectionchanged_Eventhandler_of_Listbox">
                                                <ListBox.ItemContainerStyle>
                                                    <Style TargetType="ListBoxItem">
                                                        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                                                    </Style>
                                                </ListBox.ItemContainerStyle>
                                                <ListBox.ItemTemplate>
                                                    <DataTemplate>
                                                        <Grid Height="80" VerticalAlignment="Top">
                                                            <Grid.ColumnDefinitions>
                                                                <ColumnDefinition Width="auto" />
                                                                <ColumnDefinition Width="0.70*" />
                                                                <ColumnDefinition Width="auto" />
                                                            </Grid.ColumnDefinitions>
                                                            <Image Grid.Column="0" Grid.Row="0" x:Name="img_selected" Source="{Binding selectedImage}" Width="26" Height="29"></Image>
                                                            <TextBlock Grid.Column="1" Grid.Row="0"  x:Name="fullName" Text="{Binding fullName}" Foreground="#FF4C6383" FontFamily="/Membr;component/Assets/Fonts/Fonts.zip#Source Sans Pro" Height="50" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0" />
                                                        </Grid>
                                                    </DataTemplate>
                                                </ListBox.ItemTemplate>
                                            </ListBox>

我错过了什么?而且似乎我只能在每个列表项上点击一次?

点击列表框项时更新列表框项

您可以通过以下几种方式实现:

1)从INotifyPropertyChanged继承自定义类

public class MemberUser : INotifyPropertyChanged
{
    public int member_id { get; private set; }
    public String first_name { get; private set; }
    public String last_name { get; private set; }
    public string fullName
    {
        get
        {
            return String.Format("{0} {1}", first_name, last_name);
        }
    }
    public bool IsSelected
    {
        get
        {
            return _isSelected;
        }
        set
        {
            _isSelected = value;
            OnPropertyChanged("selectedImage");
        }
    }
    private bool _isSelected;
    public string selectedImage
    {
        get
        {
            if (IsSelected)
            {
                return "/Assets/ic_selected.png";
            }
            else
            {
                return "/Assets/ic_not_selected.png";
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

2)通过Converter将ImageSource绑定到IsSelected属性

<Image Grid.Column="0" Grid.Row="0" x:Name="img_selected" Source="{Binding IsSelected, Converter={StaticResource SelectedImageConverter}}" Width="26" Height="29"></Image>

public class SelectedImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            var isSelected = (bool)value;
            return isSelected
                ? "/Assets/ic_selected.png"
                : "/Assets/ic_not_selected.png";
        }
        catch (Exception)
        {
            return "/Assets/ic_not_selected.png";
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

如果问题不是图像路径,我认为你需要实现INotifyPropertyChanged接口,在MemberUser类中,当你设置Selected属性时,也通知SelectedImage属性的变化。比如:

private bool _selected;
public bool Selected
{
   get{ return _selected;}
   set
   {
       if(value!=_selected)
       {
           _selected=value;
           OnPropertyChanged("Selected");
           OnPropertyChanged("SelectedImage");
       }
   }
}
private void OnPropertyChanged([CallerMemberName] string propertyName="")
{
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
}

Try

    public ImageSource selectedImage
            {
ImageSource temp;
                get{
                    if (selected)
                    {
                          temp=new BitmapImage(new Uri("ms-appx:////Assets/ic_selected.png", UriKind.RelativeOrAbsolute)); 
                        return temp ;
                    }
                    else
                    {
temp=new BitmapImage(new Uri("/Assets/ic_not_selected.png", UriKind.RelativeOrAbsolute));
                        return temp ;
                    }
                }
            }

因为Source of image绑定到一个ImageSource而不是字符串。检查你的url是否需要ms-appx:////。(它确实在windows 8.1应用程序)你还需要添加一个INotifyProperty changed扩展,以便能够看到属性被立即更改