在WPF项目中,我使用MVVM模式。
我尝试将集合中的项绑定到UserControl
,但所有内容都默认值为DependcyProperty
。
Window 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();
我始终在default_from_control
获得DebugControlTextBlock
值,但在DebugTextBlock
获取the_real_connection
即使我在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;
}
}
请参阅github上的解决方案。 那么,当我将模型绑定到DependcyProperty时会发生什么?
答案 0 :(得分:0)
我建议您尝试将Sessions属性设为DependencyProperty。否则,您可能必须为Sessions属性手动提升PropertyChanged。