【发布时间】:2016-07-12 04:37:19
【问题描述】:
我正在使用 mvvm 模式做一个简单的项目。它大约有一个列表,每一行都有一个文本框和删除按钮,并且在
但是我们有一个文本框并添加这样的按钮:
name1 按钮删除
name2 按钮删除
name3 按钮删除
.
.
文本框按钮添加
单击按钮删除该行应删除,单击按钮添加文本框的文本应作为新文本插入列表中
行。
我有三层 Sepand.WPFProject.Model , Sepand.WPFProject.ViewModel , Sepand.WPFProject.View;
在模型中,我有上下文、存储库和模型(这里我的模型是具有名称和 ID 属性的类别)类。仓库是这样的:
public class ModelRepository<T>
where T : class
{
ModelDbContext ctx = new ModelDbContext();
public IQueryable<T> GetAll()
{
IQueryable<T> query = ctx.Set<T>();
return query;
}
public void Add(T entity)
{
ctx.Set<T>().Add(entity);
ctx.SaveChanges();
}
public void Delete(T entity)
{
ctx.Set<T>().Remove(entity);
ctx.SaveChanges();
}
在 viewModel 中,我有这样的 categoryViewModel 类:
public class CategoryViewModel
{
ModelRepository<Category> repository = new ModelRepository<Category>();
ObservableCollection<Category> categories = new ObservableCollection<Category>();
Category category = new Category();
public ObservableCollection<Category> GetAll()
{
IQueryable<Category> categoryRepository = repository.GetAll();
foreach (Category Category in categoryRepository)
categories.Add(Category);
return categories;
}
public ObservableCollection<Category> GetAllCategories
{
get { return GetAll(); }
}
public string TxtName
{
get { return category.Name; }
set { category.Name = value; }
}
在我后面的代码中查看
this.DataContext = new CategoryViewModel();
在 XAML 中我有
<Window.Resources>
<DataTemplate x:Key="CategoryTemplate">
<Border Width="400" Margin="5" BorderThickness="1" BorderBrush="SteelBlue" CornerRadius="4">
<StackPanel Grid.Row="0" Orientation="Horizontal">
<TextBlock Width="300" Margin="5" Text="{Binding Path=Name}"></TextBlock>
<Button Name="btnDeleteCategory" Width="50" Margin="5" Click="btnDeleteCategory_Click" >-</Button>
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
.
.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Grid.Column="0" Grid.Row="0" Name="lstCategory" ItemTemplate="{StaticResource CategoryTemplate}" ItemsSource="{Binding Path=GetAllCategories}"/>
<StackPanel Margin="5" Grid.Column="0" Grid.Row="1" Orientation="Horizontal">
<Label Content="Name : "/>
<TextBox Name="TxtName" Text="{Binding Path=TxtName ,Mode=TwoWay}" Width="260"/>
<Label Width="50"/>
<Button Width="50" Content="+" Name="btnAddCategory" Click="AddCategory_Click" />
</StackPanel>
</Grid>
</Grid>
现在当我运行应用程序时,列表框填充了数据库中的数据;但我无法为 addbutton 和
编写代码删除按钮;
谁能告诉我该怎么办?
为什么我无法将列表中文本框的文本绑定到 CategoryViewModel 类的 TxtName 属性?
我是说这里
<TextBlock Width="300" Margin="5" Text="{Binding Path=Name}"></TextBlock>
当我编写 Binding Path=TxtName 时,列表框不会显示数据,而是使用 Binding Path=Name
它显示来自数据库的数据
【问题讨论】:
-
你的问题到底是什么?
-
对不起,我忘了问主要问题现在我问我的主要问题
-
您的问题仍然无法解决,对不起。 stackoverflow.com/help/how-to-ask
-
通过仔细阅读问题,我对您的问题有一个模糊的概念,但除了猜测答案之外,没有什么比猜测更好的了。尝试将您的问题分成小块,仅附加必要的代码并发布新问题