我正在尝试在ListView.ItemTemplate中使用自定义控件。此自定义控件具有对象属性。我无法绑定到此对象属性。我尝试了以下但是抛出了错误。
我的要求是,MyDataRowProperty需要绑定到分配给listView.ItemsSource的List中的每个MyDataRow。
<ListView x:Name="listView" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<!--<Controls:DetailItemControl Height="105" Width="400" MyDataRowProperty="{Binding RelativeSource={RelativeSource Self}}"></Controls:DetailItemControl>-->
<Controls:DetailItemControl Height="105" Width="400" MyDataRowProperty="{Binding}"></Controls:DetailItemControl>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
代码背后:
List<MyDataRow> rows = new List<MyDataRow>();
rows = GetData();
listView.ItemsSource = rows;
MyControl.xaml
<UserControl
x:Class="MyProject.Controls.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="110"
d:DesignWidth="400">
<Grid>
<TextBlock x:Name="tblDescription" />
</Grid>
</UserControl>
MyControl.xaml.cs:
private MyDataRow _MyDataRow;
public MyDataRowProperty MyDataRow
{
get { return _MyDataRow; }
set {
_MyDataRow = value;
if (_MyDataRow != null)
{
tblDescription.Text = _MyDataRow.Description
}
}
}
MyDataRow.cs
public class MyDataRow
{
public string Description { get; set; }
}
答案 0 :(得分:0)
有一些问题需要解决。首先,您应该绑定ViewModel中的项目,而不是后面的代码。在ViewModel中实现INotifyPropertyChanged接口。它应该是这样的:
public class YourViewModel: INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection <MyDataRow> rows;
public ObservableCollection<MyDataRow> Rows
{
get {return rows;}
set {
Rows = value;
NotifyPropertyChanged("Rows");
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
....
}
在组件中,您应该创建依赖项属性:
public string MyDataRow
{
get { return (string)GetValue(MyDataRowProperty); }
set { SetValue(MyDataRowProperty, value); }
}
public static readonly DependencyProperty MyDataRowProperty = DependencyProperty.Register("MyDataRow", typeof(string), typeof(MyControl));
在View的代码后面设置datacontext,然后你就可以在xaml中绑定它。
<ListView x:Name="listView" ItemsSource="{Binding Rows}">
<ListView.ItemTemplate>
<DataTemplate>
<Controls:DetailItemControl Height="105" Width="400" MyDataRow="{Binding Description}"></Controls:DetailItemControl>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
希望这会有所帮助。随意问。我没有运行此代码,所以检查语法,但想法就在那里。 克里斯托夫