C# 无法从WPF中的集合绑定模型的DependencyProperty
在WPF项目中,我使用MVVM模式。 我试图将集合中的一个项绑定到C# 无法从WPF中的集合绑定模型的DependencyProperty,c#,wpf,xaml,mvvm,data-binding,C#,Wpf,Xaml,Mvvm,Data Binding,在WPF项目中,我使用MVVM模式。 我试图将集合中的一个项绑定到UserControl,但所有内容都会获得默认值dependcroperty 窗口xaml: <ListView VerticalAlignment="Stretch" HorizontalAlignment="Stretch" ItemsSource="{Binding Sessions}"> <
UserControl
,但所有内容都会获得默认值dependcroperty
窗口xaml:
<ListView VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
ItemsSource="{Binding Sessions}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="DebugTextBlock" Background="Bisque"
Text="{Binding Connection}"/>
<usercontrol:SessionsControl Model="{Binding Converter=
{StaticResource DebugConverter}}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在sessioncontrol
中,我创建dependencProperty
:
//Dependency Property
public static readonly DependencyProperty ModelProperty =
DependencyProperty.Register("Model", typeof(SessionModel),
typeof(SessionsControl), new PropertyMetadata(new SessionModel("default_from_control")));
// .NET Property wrapper
public SessionModel Model
{
get { return (SessionModel)GetValue(ModelProperty); }
set { if (value != null) SetValue(ModelProperty, value); }
}
并使用此xaml以以下形式显示连接:
<TextBlock Name="DebugControlTextBlock" Background="Gray" Text="{Binding Connection}"/>
我总是从DebugControlTextBlock
中的control
中获取default\u值,但在DebugTextBlock
中获取实际连接
即使我在DebugConverter
中设置了断点,我也会看到该值是default
。
DebugConverter
只是检查正确绑定的包装器:
public class DebugConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Debug.WriteLine("DebugConverter: " + (value!=null?value.ToString():"null"));
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
请参阅上的解决方案。
那么,当我将模型绑定到DependencyProperty时会发生什么呢?我建议您尝试将会话属性也设置为DependencyProperty。否则,您可能必须手动提升会话属性的PropertyChanged。首先,我在初始化窗口之前初始化了会话的集合,其次,我已经提升了会话的PropertyChanged
(请参阅已更正的主题).我们必须先看看你的DebugConverter是什么样子,才能在这里有所帮助。如果您看到了字符串连接属性的绑定工作,那么您的绑定是正确的。此外,您不需要将会话设置为依赖属性。当您使用MVVM时,ObservableCollection不需要像其他属性那样工作。当集合更改时,ObservableCollection将向UI发出自己的通知。在这种情况下,只有在侦听整个集合被更改时,才会进行绑定。我添加了DebugConverter
的定义。我知道,Sessions
列表对于通知来说太胖了:WindowsModel
稍后将使用。看起来您只是返回了相同的内容。您的调试写线工作正常吗?在控件中绑定模型后,您如何使用该模型可能会出现问题。在DebugConverter
中,在textBlock和窗口中,我始终会获得默认值。请尝试以下操作:
,然后查看此操作是否有效。嗯
<TextBlock Name="DebugControlTextBlock" Background="Gray" Text="{Binding Connection}"/>
var windowModel = new WindowsModel();
var window = new SessionWindow(windowModel);
window.ShowDialog();
public class DebugConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Debug.WriteLine("DebugConverter: " + (value!=null?value.ToString():"null"));
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}