我在通过mvvm模式使用ICommand从数据库填充列表视图时遇到问题。我错过了一些简单的东西,或者我没有以正确的方式编写代码。
当我在没有ICommand的情况下尝试它时,它可以工作,但是ICommand并不是问题,因为它可以通过显示MessageBox来工作。
错误: System.Windows.Data信息:10:无法使用绑定检索值,并且不存在有效的后备值;请参见使用默认值代替。 BindingExpression:Path = NonFrozenColumnsViewportHorizontalOffset; DataItem = null;目标元素是“ ColumnDefinition”(HashCode = 40158284);目标属性为“宽度”(类型为“ GridLength”)
<ListView x:Name="listViewPorducts" Grid.Column="1" Margin="0" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Grid.Row="2" ItemsSource="{Binding ProductsListView}" BorderThickness="1">
<ListView.ItemTemplate>
<DataTemplate>
<Grid >
<TextBlock Name="itemName" Grid.Row="0" Margin="0,0,0,4" Text="{Binding Path=product_name}" FontSize="16" FontFamily="Calibri" TextWrapping="Wrap" TextTrimming="WordEllipsis" Background="#FFB2ACAC" HorizontalAlignment="Stretch"/>
<Separator HorizontalContentAlignment="Stretch" VerticalAlignment="Bottom"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,3,0,3">
<TextBlock Name="categoryType" Text="{Binding Path=category_name}" HorizontalAlignment="Stretch" FontSize="14" FontFamily="Calibri"/>
<TextBlock Grid.Row="1" Text="->" Margin="4,0,4,0" FontSize="14" FontFamily="Calibri"/>
<TextBlock Name="itemBrand" Text="{Binding Path=brand_name}" HorizontalAlignment="Stretch" FontSize="14" FontFamily="Calibri"/>
</StackPanel>
<TextBlock Name="itemPrice" Grid.Row="2" Margin="0,3,0,3" Text="{Binding Path=list_price, StringFormat={}{0:C}}" FontSize="16" FontFamily="Calibri" FontWeight="Bold" HorizontalAlignment="Left"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
// Class1
DataTable dataTable;
public DataView ProductsListView { get; private set; }
public void GetData()
{
string conStr = ConfigurationManager.ConnectionStrings["EYEWEAR"].ToString();
try
{
SqlConnection sqlCon = new SqlConnection(conStr);
dataTable = new DataTable();
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand("SELECT p.product_name, ct.category_name, bt.brand_name, p.list_price FROM dbo.products p LEFT JOIN brands_Table bt ON p.brand_id = bt.brand_id LEFT JOIN categoriesTable ct ON p.category_id = ct.category_id; ", sqlCon);
adapter.Fill(dataTable);
ProductsListView = dataTable.DefaultView;
}
}
sqlCon.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
// ShowFrames:ICommand
public void Execute(object parameter)
{
MessageBox.Show("Click command works.");
class1.GetData();
}