好的,我有一个容器,我为其创建了两个数据模板。基本上,一个模板将显示 5 个文本框,其中绑定了对象数据,另一个模板将显示一个按钮以添加该特定对象。我对 DataTemplateSelector 进行了子类化,它可以工作,但是当我浏览我的记录时,选择器再也不会被调用。
那么我将如何让容器重新选择它的模板。该容器是一个 StackPanel,我已经尝试过 UpdateVisuals、InvalidateVisuals、InvalidateArrange 和 ApplyTemplate。
XAML 代码
<DataTemplate x:Key="advisorTemplate">
<StackPanel Orientation="Vertical" Margin="2,2,2,2" HorizontalAlignment="Stretch" VerticalAlignment="Top">
<StackPanel Orientation="Horizontal" Margin="2,2,2,2" HorizontalAlignment="Center">
<extToolkit:WatermarkTextBox Name="txtAcadAdv" Watermark="Acad Adv" Width="125" Margin="2" Text="{Binding Path=Adv.AcadAdv}"/>
<extToolkit:WatermarkTextBox Name="txtProgAdv" Watermark="Prog Adv" Width="125" Margin="2" Text="{Binding Path=Adv.ProgAdv}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="2,2,2,2" HorizontalAlignment="Center">
<extToolkit:WatermarkTextBox Name="txtPortAdv" Watermark="Port Adv" Width="125" Margin="2" Text="{Binding Path=Adv.PortAdv}"/>
<extToolkit:WatermarkTextBox Name="txtEleTws" Watermark="Ele Tws" Width="125" Margin="2" Text="{Binding Path=Adv.EleTws}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="2,2,2,2" HorizontalAlignment="Center">
<extToolkit:WatermarkTextBox Name="txtMatTws" Watermark="Mat Tws" Width="125" Margin="2" Text="{Binding Path=Adv.MatTws}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="addAdvisor">
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2" Name="btnAddAdvisor" Click="ButtonClick" Content="Add Advisor"/>
</DataTemplate>
初始化组框上更改的内容
grpAdv.ContentTemplateSelector = _advisorSelector;
最后是选择器代码
private readonly StudentWin _win;
public AdvisorDataTemplateSelector(StudentWin win)
{
_win = win;
}
public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
var sp = item as StackPanel;
var adv = sp.DataContext as Advisor;
if (adv == null)
return _win.FindResource("addAdvisor") as DataTemplate;
return _win.FindResource("advisorTemplate") as DataTemplate;
}
这是我的导航代码片段
case "btnNext":
{
if(_view.CurrentPosition < _view.Count - 1)
{
CheckForUnusedReferences(_view.GetItemAt(_view.CurrentPosition) as Student);
_view.MoveCurrentToNext();
CheckForNullReferences(_view.CurrentPosition);
grpAdv.ApplyTemplate();
}
}
这两种附加方法是检查学生的关系是否为空,他们将为我创建它并将其添加到数据上下文中,否则实体框架将不会保存更改。上面的数据模板基本上可以帮助我解决在尝试创建新学生时没有 studentId 的问题。