我的问题是我的数据网格填充了如下代码:
(...)
while (rdr.Read())
{
dataGrid1.Items.Add(new Produkt { nazwa = rdr.GetString(rdr.GetOrdinal("nazwa")), cena = rdr.GetString(rdr.GetOrdinal("cena")), kod = rdr.GetString(rdr.GetOrdinal("kod")) });
}
(...)
但在我声明我的数据网格中的所有列之前:
DataGridTextColumn col1 = new DataGridTextColumn();
DataGridTextColumn col2 = new DataGridTextColumn();
DataGridTextColumn col3 = new DataGridTextColumn();
dataGrid1.Columns.Add(col1);
dataGrid1.Columns.Add(col2);
dataGrid1.Columns.Add(col3);
col1.Binding = new Binding("nazwa");
col2.Binding = new Binding("cena");
col3.Binding = new Binding("kod");
col1.Header = "nazwa";
col2.Header = "cena";
col3.Header = "kod";
现在我已经通过输入的文本添加了过滤,所以我在datagrid(每列)下有3个textBox但它们的宽度不像datagrid中的列的宽度。我试过像textbox1.width = datagrid.columns[1].width
这样的想法,但那不起作用。
有人知道我的问题的解决方案吗?
感谢您的回答!
PS。我不能只喜欢声明宽度(f.e. textbox.width = 200
)
答案 0 :(得分:3)
尝试类似的东西:
XAML文件:
<Window x:Class="GridAutoWidth.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>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<DataGrid Name="dgProducts" ItemsSource="{Binding Products}" />
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ElementName=dgProducts, Path=Columns[0].ActualWidth}" />
<ColumnDefinition Width="{Binding ElementName=dgProducts, Path=Columns[1].ActualWidth}" />
<ColumnDefinition Width="{Binding ElementName=dgProducts, Path=Columns[2].ActualWidth}" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" />
<TextBox Grid.Column="1" />
<TextBox Grid.Column="2" />
</Grid>
</Grid>
</Window>
代码隐藏文件:
using System.Windows;
namespace GridAutoWidth
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
}
MainViewModel:
using System.Collections.ObjectModel;
namespace GridAutoWidth
{
class MainViewModel
{
public MainViewModel()
{
for (int i = 0; i < 10; i++)
{
Products.Add(new Product
{
Name = "Name " + i,
Price = (decimal)(18 * (i + 8.4)),
Code = "Sample code " + i
});
}
}
private ObservableCollection<Product> _products = new ObservableCollection<Product>();
public ObservableCollection<Product> Products
{
get { return _products; }
set { _products = value; }
}
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Code { get; set; }
}
}