1

我在尝试将控件绑定到数据源时遇到了很多麻烦。我尝试绑定到 XML 文档。这行得通,但是当我尝试刷新 XML 文档本身并让它更新 UI 时出现了很多问题。

我最新的尝试是将我的控件绑定到一个 DataView,这看起来很简单。我在 StackOverflow 上找到了一个示例应用程序,它执行以下操作:

    public MainWindow()
    {

        InitializeComponent();

        DataTable dataTable = GetTable();
        Binding dataTableBinding = new Binding();
        dataTableBinding.Source = dataTable;
        dataTableBinding.Path = new PropertyPath("Rows[0][MyTextColumn]");
        txtMyTextColumnDataTable.SetBinding(TextBox.TextProperty, dataTableBinding);

        DataView dataView = dataTable.DefaultView;
        Binding dataViewBinding = new Binding();
        dataViewBinding.Source = dataView;
        dataViewBinding.Path = new PropertyPath("[0][MyTextColumn]");
        txtMyTextColumnDataView.SetBinding(TextBox.TextProperty, dataViewBinding);
    }

这非常有效,开箱即用。我添加了一个按钮,其代码会更新数据表中的值,当我单击该按钮时,文本框会立即反映新值。

我在我的 VB.Net 项目中尝试了这个,如下所示:

    dim plcData As DataTable = GetTable()
    dim plcView As DataView = plcData.DefaultView
    dim plcBinding As Binding = New Binding
    plcBinding.Source = plcView
    plcBinding.Path = New PropertyPath("(0)(conveyor_plc_data_Main_FeedCarousel_caroAngle)")
    Me.tb.SetBinding(TextBlock.TextProperty, plcBinding)

它不起作用。它不会更新我的 UI 控件。在这两种情况下,GetTable 都会使用示例数据构建一个 1 行 DataTable。在我的 VB 项目中,tb 是 MainWindow 上的一个 TextBlock。

在 VB 项目中,我可以中断我的代码并在即时窗口中查询特定的数据列,并且正确的值在那里。它只是不会更新到我的控制范围内。

这似乎是一件非常简单的事情。我对 WPF 很陌生,看不出我的代码有什么问题。最终我想在我的 XAML 中定义绑定,但不知道如何做到这一点。此时,绑定的代码隐藏设置就可以了。我将有许多控件绑定到许多数据列。

谁能告诉我我在这里遗漏了什么明显的东西?

4

1 回答 1

2

根据文档PropertyPath该类的语法仅接受 C# 样式的索引器。

立即对象上的单个索引器作为数据上下文:

<Binding Path="[key]" .../>

该类无法根据调用语言更改其语法。


编辑
要在代码隐藏中创建时在 XAML 中设置绑定DataView,请将视图公开为属性:

public static readonly DependencyProperty plcViewProperty 
   = DependencyProperty.Register("plcView", typeof(System.Data.DataView), 
   typeof(MainWindow), new PropertyMetadata(null));

public System.Data.DataView plcView
{
   get { return (System.Data.DataView)GetValue(plcViewProperty); }
   set { SetValue(plcViewProperty, value); }
}

private void MainWindow_Initialized(object sender, EventArgs eventArgs)
{
   plcView = GetTable().DefaultView;
}

然后在您的 XAML 中:

<Window x:Name="TheWindow" ...>
   ...
   Text="{Binding ElementName=TheWindow,
      Path=plcView[0][conveyor_plc_data_Main_FeedCarousel_caroAngle]}"
于 2013-03-18T19:27:38.143 回答