我是新来WPF和整个数据绑定的东西。我读了几篇文章,对于如何将数据绑定到UI元素我感到很困惑。了解DataBinding
我看到一个帖子做这种方式:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="myWindow">
<Grid>
<TextBox Text="{Binding Path=Speed, ElementName=myWindow}" />
</Grid>
</Window>
这是假设Speed
是在代码隐藏文件中定义的属性/成员。其他一些人使用静态资源命名绑定,并引用该名称和其他名为DataContext
的名称以用于绑定。现在,因为我对WPF的数据绑定很陌生,所以我很不确定是否存在任何有关使用哪种数据绑定的最佳实践方法。
基本上我想知道为什么必须有几个class-property被定义为底层viewmodel的一种连接器,我虽然这个东西更“动态”。
我只瞄准了XAML文件,而不需要在文件后面的* .xaml.cs代码中添加任何东西。例如:我有一个名为MainWindowViewModel
的类(它将代表我的ViewModel)拥有ObservableCollection<string>
类型的成员,并且我想将ListBox
(在我的视图中)绑定到此集合。到目前为止,我得到这个工作的唯一方法是使用第一种情况,即ElementName
,我必须为视图类添加一个属性作为一种连接器。就像这样:
MainWindow.xaml:
<Window x:Class="Sample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="MW" Title="MainWindow" Height="419" Width="463">
<Grid>
<ListBox ItemsSource="{Binding ElementName=MW, Path=ListerResultConnector}" />
</Grid>
</Window>
MainWindow.xaml.cs:
private ObservableCollection<string> mListerResultData = MainWindowViewModel.Instance.RetrievalStringResults;
public ObservableCollection<string> ListerResultConnector
{
get { return mListerResultData; }
}
我的问题是,如果因为使用存在将数据绑定到我UI的明智之选作为代码隐藏文件中的“连接器”属性。
请看看这些相关的问题: - http://stackoverflow.com/questions/7472/wpf-databinding http://stackoverflow.com/questions/6807006/c-sharp-databinding-tutorial –