我整天都在尝试这个,但没有任何运气。我能够显示 UserControl,但我无法弄清楚为什么即使我在 XAML 中设置了列也不会显示。另外,我不确定数据是否显示,因为表单打开为空白。
这是我从另一个程序调用的类库的一部分。但是,它总是显示一个空白表单,并且没有任何更新。
下面是我的用户控件代码。
public partial class DisplayData : UserControl
{
ObservableCollection<Data> _DataCollection = new ObservableCollection<Data>();
public DisplayData()
{
InitializeComponent();
Window window = new Window();
window.Content = new UserControl();
window.Show();
}
public void AddDataToList(int ID, string Name)
{
_DataCollection.Add(new Data
{
StudentID = ID,
StudentName = Name
});
}
public ObservableCollection<Data> DataCollection { get { return _DataCollection; } }
}
public struct Data
{
public int StudentID { get; set; }
public string StudentName { get; set; }
}
下面是我如何称呼它:
class Program
{
[STAThread]
static void Main(string[] args)
{
DisplayData displayData = new DisplayData();
displayData.AddDataToList(2, "John");
System.Threading.Thread.Sleep(5000);
}
}
和 xaml:
<UserControl x:Class="ConsoleApplication1.DisplayData"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="210">
<StackPanel>
<ListView ItemsSource="{Binding DataCollection}">
<ListView.View>
<GridView>
<GridViewColumn Width="100" Header="ID" DisplayMemberBinding="{Binding StudentID}" />
<GridViewColumn Width="100" Header="Name" DisplayMemberBinding="{Binding StudentName}" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</UserControl>
编辑我还想补充一点:
- 它不会显示正确的尺寸
- 我什至看不到表格上的列标题
- 也没有数据更新。
另外,不确定这是否有帮助,但我已将其作为 WPF UserControl 添加到我现有的项目中。