我是XAML和数据绑定的新手.我想在MainWindow.xaml中定义一个GUI控件,该控件从MainWindow.xaml.cs中的成员变量获取其数据.为简单起见,我只创建了一个显示计数器的程序以及一个增加计数器的按钮.
基于earlier threads我抬起头来,我想出了以下代码:
MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace XAMLBindingTest { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private int Counter { get { return (int)GetValue(CounterProperty); } set { SetValue(CounterProperty,value); } } public static readonly DependencyProperty CounterProperty = DependencyProperty.Register("Counter",typeof(int),typeof(MainWindow),new PropertyMetadata(null)); public MainWindow() { Counter = 0; InitializeComponent(); } private void incrementCounter(object sender,RoutedEventArgs e) { ++Counter; } } }
MainWindow.xaml
<Window x:Class="XAMLBindingTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="140" Width="180"> <Grid> <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top"> <TextBlock x:Name="txbCounter" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Counter}" VerticalAlignment="Top"/> <Button x:Name="btnIncrement" Content="Increment" Width="75" Click="incrementCounter"/> </StackPanel> </Grid> </Window>
此示例编译,但TextBlock未显示计数器值.如何以正确的方式将TextBlock连接到Counter成员?
解决方法
尝试在窗口中添加“名称”并使用“ElementName”绑定
<Window x:Class="XAMLBindingTest.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" Name="UI"> <Grid> <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top"> <TextBlock x:Name="txbCounter" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding ElementName=UI,Path=Counter}" VerticalAlignment="Top"/> <Button x:Name="btnIncrement" Content="Increment" Width="75" Click="incrementCounter"/> </StackPanel> </Grid> </Window>