在WPF项目中,我使用MVVM模式。 我尝试将集合中的项目绑定到UserControl
,但所有内容均获取默认值DependcyProperty
。无法绑定WPF中收集模型的依赖属性
的窗口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>
哪里会议是
private ObservableCollection<SessionModel> _sessions;
public ObservableCollection<SessionModel> Sessions
{
get { return _sessions; }
set
{
if (Equals(value, _sessions)) return;
_sessions = value;
OnPropertyChanged("Sessions");
}
}
的SessionModel:
public class SessionModel:ViewModelBase
{
private string _connection;
public string Connection
{
get { return _connection; }
set
{
if (value == _connection) return;
_connection = value;
OnPropertyChanged("Connection");
}
}
}
在SessionsControl
我创建DependencyProperty
:
//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}"/>
所以,当我运行的应用程序
var windowModel = new WindowsModel();
var window = new SessionWindow(windowModel);
window.ShowDialog();
我总是在DebugControlTextBlock
得到default_from_control
值,但在DebugTextBlock
得到the_real_connection
即使我在中设置断点我看到这个值是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;
}
}
请参阅解决方案上github。 那么,当我将模型绑定到DependcyProperty时会发生什么?
我们必须看看您的DebugConverter在这里有什么样的帮助。如果您看到字符串Connection属性的绑定工作,那么您正在正确地进行绑定。 此外,您不需要使您的会话成为依赖项属性。当您使用MVVM时,ObservableCollection不需要像其他属性那样工作。当集合更改时,ObservableCollection会将其自己的通知提交给UI。在这种情况下,你的绑定只有在你正在倾听整个集合被更改的情况下。 –
我添加了'DebugConverter'的定义。我知道'Sessions'列表对于通知来说太胖了,稍后会使用'WindowsModel'。 –
看起来你只是回来了同样的事情。您的调试WriteLine工作正常吗?这可能是一个问题,因为一旦模型被绑定到控件中,您将如何使用该模型。 'DebugConverter'中的 –