我在代码背后Text
依赖属性代码反之亦然。数据绑定到后面
<Label Content="{Binding ???}" />
我该怎么办?
我已经做了一段时间之前,但现在我不记得如何 - 它是非常简单的。最简单的代码将被接受。
我在代码背后Text
依赖属性代码反之亦然。数据绑定到后面
<Label Content="{Binding ???}" />
我该怎么办?
我已经做了一段时间之前,但现在我不记得如何 - 它是非常简单的。最简单的代码将被接受。
设置你的窗口/控制同一类的DataContext的,然后指定的结合,像这样的路径:
public class MyWindow : Window {
public MyWindow() {
InitializeComponents();
DataContext = this;
}
public string Text { ... }
}
然后在您的xaml中:
<Label Content="{Binding Path=Text}">
它的工作表示感谢。但为什么它没有在VS设计器中显示'Label'内容?! – drasto 2011-04-28 20:58:24
从代码隐藏设置DataContext时,blend不会显示绑定到数据上下文的数据。您可以使用d:DataContext将设计时数据上下文设置为便于在混合中进行设计的另一个对象。看到这里:http://stackoverflow.com/questions/862829/what-is-the-advantage-of-setting-datacontext-in-code-instead-of-xaml – 2011-04-28 21:07:40
我不想它在混合但在VisualStudio 。它是一样的吗? – drasto 2011-04-28 21:12:59
你必须设置窗口的DataContext使其工作。 XAML:
<Window x:Class="WpfApplication2.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"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<StackPanel>
<Label Content="{Binding Text}" />
<Button Content="Click me" Click="HandleClick" />
</StackPanel>
</Grid>
</Window>
代码隐藏:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MainWindow), new PropertyMetadata("Hello world"));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { this.SetValue(TextProperty, value); }
}
public MainWindow()
{
InitializeComponent();
}
protected void HandleClick(object sender, RoutedEventArgs e)
{
this.Text = "Hello, World";
}
}
在XAML设置的DataContext到代码隐藏可以是一个有点棘手,但一般来说,这些情况是最常见的:
。
<Window
blahhhh..
DataContext={Binding RelativeSource={RelativeSource Mode=Self}}>
或
<UserControl
Blahhhh....
DataContext={Binding RelativeSource={RelativeSource Mode=Self}}>
2。如果设置了DataContext的窗口或用户控制比后面的代码别的什么,并有一个孩子的控制,你将需要设置它的的DataContext到代码的背后,您可以使用以下方法:
<Label DataContext={Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}/>
定制用户控件:
<Label DataContext={Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}/>
在这种情况下,的DataContext设置自会作出具有约束力的参考标签对象本身不是控制的代码隐藏。我希望这会有所帮助。
我试过这个:''并且它也不起作用。 。它可能是绑定不起作用的全新WPF项目中的一切工作? – drasto 2011-04-28 20:48:22