我创建了一个类,我需要像其他UI控件一样拥有Visibility属性。它看起来像这样:
更多扩展代码:
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;
}
}
}
我尝试做的是像过滤器(搜索),我想要隐藏项目。只是在类中添加属性也不起作用。
答案 0 :(得分:0)
你非常接近......为了让你的类工作MyClass必须实现INotifyPropertyChanged,我使用基类bindable,这使得实现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;
}
}
}