将可见性属性实现到自定义类
本文关键字:自定义 实现 可见性 属性 | 更新日期: 2024-11-08 06:36:54
我创建了一个类,我需要像其他UI控件一样具有可见性属性。它看起来像这样:
更多扩展代码:
XAML:
<ListBox x:Name="itemsHolder" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Surname}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
代码隐藏:
public ObservableCollection<MyClass > myVM= new ObservableCollection<MyClass>();
public class MyClass : Control //FrameworkElement
{
public string Name { get; set; }
public string Surname { get; set; }
}
...
MyClass my1 = new MyClass();
my1.Name = "Test";
my1.Surname = "Test2";
myVM.Add(my1);
itemsHolder.ItemsSource = myVm;
...
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
foreach(MyClass item in itemsHolder.Items)
{
if(!item.Name.Contains((sender as TextBox).Text))
{
item.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
else
{
item.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
}
}
我尝试做的是过滤器(搜索)之类的东西,我想隐藏项目。仅向类添加属性也不起作用。
你非常接近...为了让这个工作,你的类MyClass必须实现INotifyPropertyChanged,我使用基类可绑定的,这使得实现INotifyPropertyChanged变得更加简单。
以下是答案
XAML:
<ListBox Grid.Row="1" x:Name="itemsHolder" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Visibility="{Binding IsVisible}">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Surname}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
法典:
public ObservableCollection<MyClass > myVM= new ObservableCollection<MyClass>();
public class Bindable:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyClass : Bindable {
private string _Name;
public string Name {
get { return _Name; }
set
{
if (_Name != value)
{
_Name = value;
OnPropertyChanged();
}
}
}
private string _Surname;
public string Surname
{
get { return _Surname; }
set{
if (_Surname != value)
{
_Surname = value;
OnPropertyChanged();
}
}
}
public Visibility _IsVisible;
public Visibility IsVisible {
get { return _IsVisible; }
set {
if (_IsVisible != value)
{
_IsVisible = value;
OnPropertyChanged();
}
}
}
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
foreach(MyClass item in itemsHolder.Items)
{
if(!item.Name.Contains((sender as TextBox).Text))
{
item.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
else
{
item.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
}
}