C# 在WPF Xaml中检索并保存动态添加的控件?
我有一个添加按钮——当我通过命令单击它时,我会将它添加到集合中C# 在WPF Xaml中检索并保存动态添加的控件?,c#,wpf,xaml,C#,Wpf,Xaml,我有一个添加按钮——当我通过命令单击它时,我会将它添加到集合中 <ItemsControl ItemsSource="{Binding Collection}"> <ItemsControl.ItemTemplate> <DataTemplate> <Grid DataContext="{StaticResource VieWMode
<ItemsControl ItemsSource="{Binding Collection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid DataContext="{StaticResource VieWModel}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="15*"/>
<ColumnDefinition Width="40*"/>
</Grid.ColumnDefinitions>
<Label Content="GH" Grid.Row="0" Grid.Column="0" VerticalContentAlignment="Center"></Label>
<tk:RadComboBox Grid.Row="0" Grid.Column="0" Margin="10" IsFilteringEnabled="True" Width="150" DisplayMemberPath="D" IsEditable="True" ItemsSource="{Binding GK}" SelectedItem="{Binding SK, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</tk:RadComboBox>
<Label Content="HB" Grid.Row="0" Grid.Column="1" VerticalContentAlignment="Center"></Label>
<tk:RadComboBox Grid.Row="0" Grid.Column="1" Margin="10" IsFilteringEnabled="True" Name="cb" Width="350" IsEditable="True" DisplayMemberPath="D" ItemsSource="{Binding VR}" SelectedItem="{Binding VR1,Mode=TwoWay}">
</tk:RadComboBox>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
每当我单击“添加”按钮时,将添加此项目板
我的要求:
我已经没有主意了,如何做到这一点,谁都能帮上忙MVVM模式我猜您在MainViewModel中有集合,并有用于添加模型的命令
private Model _lastAdded;
public Model LastAdded
{
get{return _lastAdded;}
set{_lastAdded = value;}
}
private void AddCommand(object obj)
{
if(_lastAdded != null && _lastAdded.SelectedValue != null)
{
var newItem = new Model();
Collection.Add(newItem);
_lastAdded = newItem;
}
else
{
//Show message
}
}
使用选择器类。我已经使用CurrentInstance绑定了集合,它现在可以正常工作了在哪里添加LastAdded您能解释一下吗?我希望不会首先添加它time@SundarStalin与具有Collection和AddCommand方法的类相同。我已经将其添加到MyCollection。当我下次添加时,我的组合框必须只有值才能保存。请参阅我的编辑。。您应该在_lastAdded.SelectedValue中使用组合框选择中使用的属性。如果可以,发布模型viewmodel代码我已经更新了DemoViewModel代码。您是否可以使用viewmodel中正确的变量名更新完整的解决方案?您不支持为DataTemplate设置DataContext。当提供ItemsSource时,根据MVVM更改此选项,并查看我的答案
private Model _lastAdded;
public Model LastAdded
{
get{return _lastAdded;}
set{_lastAdded = value;}
}
private void AddCommand(object obj)
{
if(_lastAdded != null && _lastAdded.SelectedValue != null)
{
var newItem = new Model();
Collection.Add(newItem);
_lastAdded = newItem;
}
else
{
//Show message
}
}