在WINUI3应用程序中,将数据绑定到ObservableCollection可能无法正常工作。这是由于ObservableCollection的实现方式与WINUI3的新UI元素库不兼容所致。为了解决这个问题,可以尝试使用XAML Behaviors库中的DataBind库。以下是一个示例代码:
XAML:
C#:
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
Items = new ObservableCollection
private ObservableCollection _items;
public ObservableCollection Items
{
get { return _items; }
set { SetProperty(ref _items, value); }
}
// other properties and methods omitted for brevity
}
public class DataBindBehavior : Behavior
public object Binding
{
get { return GetValue(BindingProperty); }
set { SetValue(BindingProperty, value); }
}
private static void BindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (DataBindBehavior)d;
if (behavior.AssociatedObject != null)
{
if (e.NewValue != null)
{
var binding = new Binding
{
Path = new PropertyPath("DataContext." + e.NewValue.ToString()),
Mode = BindingMode.OneWay
};
behavior.AssociatedObject.SetBinding(ListViewBase.ItemsSourceProperty, binding);
}
else
{
behavior.AssociatedObject.ClearValue(ListViewBase.ItemsSourceProperty);
}
}
}
}
上一篇:bind添加zabbix监控