WPF Tips

1. About the binding expression "{Binding Path=.}" in XAML, here is one example of TreeView Control:

We can give its ItemsSource property a binding of "{Binding Path=.}", which is a way of indicating that the ItemsSource property is bound to the TreeView's DataContext.

2. One tip to use the <Run/> element in WPF

<StackPanel>

<TextBlock>

<Run FontWeight="Bold">Publisher: </Run>

<TextBlock Text="{Binding Path=Publisher}" TextWrapping="Wrap"></TextBlock> 

</TextBlock>

<TextBlock> 

<Run FontWeight="Bold">Version: </Run> 

<TextBlock Text="{Binding Path=Version}"></TextBlock> 

</TextBlock>

</StackPanel>

For such simple usage, you don't have to use the converter, just use the <Run> element to solve this issue.

 3. The DataGrid or ComboBox's SelectedItem set to null or TabControl switch:

For the SelectedItem we always use OneWayToSource binding, this is why that issues happens, seems the real reason is visual tree related. Here is one soulution, just use the TwoWay binding instead of OneWayToSource, but sometime it doesn't work.

4. 为了使用MVVM模式,将MainWindow的初始化加载操作放到了App.xaml.cs中。但出现了一个奇怪的现象,运行程序时,会加载出两个MainWindow实例,并且第二个MainWindow的datacontext为空。经单步调试发现,当OnStartUp(App.xaml.cs中)方法执行完毕之后,用重新执行了MainWindow的构造函数,由于这里只是调用了InitializeComponent,没有为其DataContex赋值,所以第二次加载的窗口没有绑定的数据。

出现这种现象是因为整个应用程序默认的运行时首次加载的页面是MainWindow窗口,需要到App.xaml中,将Application节点中的StartupUri属性删掉,你会发现这个属性默认的值是“MainWindow.xaml"。删掉之后就只会初始化一个实例了。

原文地址:https://www.cnblogs.com/CSharpSPF/p/2322571.html