我有一个如下所示的ListView:
组合框绑定到TfsTask类型的ObservableCollection对象。当用户更改选择时,我希望同一行上的控件填充组合框中所选项目中包含的数据。例如,假设任务“测试”具有特定的持续时间值和另一个剩余值。如果用户在组合框中选择此任务,我想用这些值填充行上的控件。
以下是问题:如何将其他列中的控件绑定到组合框的选定项目。直接绑定到控件时,可以使用其ElementName执行此操作,但是如何在DataTemplate中执行此操作?
以下是我在XAML中定义ListView的方法。我只将任务组合框和持续时间文本框作为示例
<ListView MinHeight="100" Name="m_taskList">
<ListView.View>
<GridView>
<GridViewColumn Width="140" Header="Task" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<ComboBox Name="m_taskName" DisplayMemberPath="Name" SelectedValue="{Binding Path=TaskId, Mode=TwoWay}" SelectedValuePath="Id" ItemsSource="{Binding ElementName=This, Path=TfsTasks}/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="140" Header="Duration" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid >
<TextBox Text="{Binding ????}" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<!-- .... -->
</GridView>
</ListView.View>
</ListView>
答案 0 :(得分:1)
它正在运行,但您必须在此解决方案中添加对象中的属性。
试试这个:
XAML文件:
<Window x:Class="ListViewCombo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListView MinHeight="100" Name="m_taskList" ItemsSource="{Binding Path=MyItems}">
<ListView.View>
<GridView>
<GridViewColumn Width="140" Header="Task" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<ComboBox Name="m_taskName" DisplayMemberPath="Name" SelectedItem="{Binding Path=SelectedItem}" SelectedValuePath="ID" ItemsSource="{Binding Path=Items}" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="140" Header="Duration" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid >
<TextBox MinWidth="150" Text="{Binding Path=SelectedItem.Duration}" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
ViewModel文件:
using System.Collections.ObjectModel;
using Microsoft.Practices.Prism.ViewModel;
namespace ListViewCombo
{
class MainViewModel : NotificationObject
{
public MainViewModel()
{
for (int i = 0; i < 3; i++)
{
ObservableCollection<Task> Source = new ObservableCollection<Task>();
for (int j = 0; j < 5; j++)
{
Source.Add(new Task { ID = i, Name = "Name_" + i, Duration = (i + 2) * 6 + (3 * j) });
}
MyItems.Add(new TfsTask { ID = i, Items = Source });
}
}
private ObservableCollection<TfsTask> _myItems = new ObservableCollection<TfsTask>();
public ObservableCollection<TfsTask> MyItems
{
get { return _myItems; }
set { _myItems = value; RaisePropertyChanged(() => MyItems); }
}
}
public class Task
{
public int ID { get; set; }
public string Name { get; set; }
public int Duration { get; set; }
}
public class TfsTask
{
public int ID { get; set; }
public ObservableCollection<Task> Items { get; set; }
public Task SelectedItem { get; set; }
}
}