我有名为RoomAndPersonsAccommodationItem的自定义控件,里面有Property Room:
public static readonly DependencyProperty roomProperty =
DependencyProperty.Register("Room", typeof(RoomData),
typeof(RoomAndPersonsAccommodationItem), new FrameworkPropertyMetadata(null));
public RoomData RoomProperty
{
get { return GetValue(roomProperty) as RoomData; }
set { SetValue(roomProperty, value); }
}
private RoomData room = null;
public RoomData Room
{
get { return room; }
set { room = value; }
}
RoomAndPersonsAccommodationItem在ListView上设置为DataTemplate:
<ListView Name="RoomsListView" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Controls:RoomAndPersonsAccommodationItem Room="{Binding Path=., Mode=TwoWay}" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在上面的ListView- RoomsListView类我有这个代码:
RoomsListView.ItemsSource = reservation.Rooms;
//reservation.Rooms is List<RoomData>
问题在于:
<Controls:RoomAndPersonsAccommodationItem Room="{Binding Path=., Mode=TwoWay}" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
我想从ListView上的ItemSource将Room属性绑定到room对象,但是我收到null。 有谁知道我哪里错了?也许在这里:Room =&#34; {Binding Path =。,Mode = TwoWay}&#34;或者在DependencyProperty声明?
由于 马丁
更新
仍然无效......结果始终为空。我尝试了很多这样的选项来绑定Tag或DataContext但没有任何反应。我想这个问题不在DependencyProperty中。它是绑定我的东西...... 这是代码:
private ReservationData reservation = null;
//Methods
private void fillForms()
{
//Logic
RoomsListView.ItemsSource = reservation.Rooms;
//Logic
}
这是带有DataTemplate的ListView:
<ListView Name="RoomsListView" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Controls:RoomAndPersonsAccommodationItem
Room="{Binding}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
RoomAndPersonsAccommodationItem中的DependencyProperty:
public static readonly DependencyProperty RoomProperty =
DependencyProperty.Register(
"Room", typeof(RoomData), typeof(RoomAndPersonsAccommodationItem),
new FrameworkPropertyMetadata(null));
public RoomData Room
{
get { return (RoomData)GetValue(RoomProperty); }
set {
SetValue(RoomProperty, value); }
}
更新2
已解决 以上来源是正确的。错误的结果来自于我在构造函数完成之前检查了Room属性。当我在构造函数之后检查结果时一切正常!谢谢!
答案 0 :(得分:0)
试试这个,该属性的一个属性和一个依赖属性:
public static readonly DependencyProperty RoomProperty =
DependencyProperty.Register(
"Room", typeof(RoomData), typeof(RoomAndPersonsAccommodationItem),
new FrameworkPropertyMetadata(null));
public RoomData Room
{
get { return (RoomData)GetValue(RoomProperty); }
set { SetValue(RoomProperty, value); }
}
您还可以删除&#34;路径&#34;从绑定来看,没有必要。