wpf如何在XAML上获取codebehind变量
在“代码隐藏”中,我们设置窗口背景的imagepath,是否有办法在xaml上获取此值并使用它设置背景图像尽管我没有使用背景图像显示,但以下绑定对于您的情况仍然有效: XAMLwpf如何在XAML上获取codebehind变量,wpf,code-behind,Wpf,Code Behind,在“代码隐藏”中,我们设置窗口背景的imagepath,是否有办法在xaml上获取此值并使用它设置背景图像尽管我没有使用背景图像显示,但以下绑定对于您的情况仍然有效: XAML <TextBox DataContext="{Binding RelativeSource={RelativeSource AncestorLevel=1,AncestorType=Window}}" Text="{Binding MyProperty}" Width="200" Height="50"/>
<TextBox DataContext="{Binding RelativeSource={RelativeSource AncestorLevel=1,AncestorType=Window}}"
Text="{Binding MyProperty}" Width="200" Height="50"/>
希望这对你有帮助 虽然我没有显示背景图像,但以下绑定仍然适用于您的情况: XAML
<TextBox DataContext="{Binding RelativeSource={RelativeSource AncestorLevel=1,AncestorType=Window}}"
Text="{Binding MyProperty}" Width="200" Height="50"/>
希望这对你有帮助 在最好的情况下,隐藏的代码为空或只有InitializeComponent存在 因此,我将强调一种实现这一点的方法,并让未来发生变化 未来变得很容易 您可以轻松地为窗口设置DataContext(例如在codebehind中) 从该DataContext(当此 路径将改变)您可以轻松地绑定到您想要的任何内容 下面是一个小例子:
// ViewModel class containing ImagePath
public class WindowBackgroundViewModel : INotifyPropertyChanged
{
public string ImagePath { get; set; }
}
// in Codebehind
public WindowBackgroundViewModel ViewModel { get; set; }
// in Constructor
public myWindow()
{
this.ViewModel = new WindowBackgroundViewModel();
this.ViewModel.ImagePath = @"C:\myBackground.png";
this.DataContext = this.ViewModel;
}
// in XAML
<... ImageBackground="{Binding Path=ImagePath}"
//包含ImagePath的ViewModel类
公共类WindowBackgroundViewModel:INotifyPropertyChanged
{
公共字符串ImagePath{get;set;}
}
//暗藏
public WindowBackgroundViewModel视图模型{get;set;}
//在构造函数中
公共myWindow()
{
this.ViewModel=新的WindowBackgroundViewModel();
this.ViewModel.ImagePath=@“C:\myBackground.png”;
this.DataContext=this.ViewModel;
}
//在XAML中
在最好的情况下,代码是空的,或者只有InitializeComponent存在
因此,我将强调一种实现这一点的方法,并让未来发生变化
未来变得很容易
您可以轻松地为窗口设置DataContext(例如在codebehind中)
从该DataContext(当此
路径将改变)您可以轻松地绑定到您想要的任何内容
下面是一个小例子:
// ViewModel class containing ImagePath
public class WindowBackgroundViewModel : INotifyPropertyChanged
{
public string ImagePath { get; set; }
}
// in Codebehind
public WindowBackgroundViewModel ViewModel { get; set; }
// in Constructor
public myWindow()
{
this.ViewModel = new WindowBackgroundViewModel();
this.ViewModel.ImagePath = @"C:\myBackground.png";
this.DataContext = this.ViewModel;
}
// in XAML
<... ImageBackground="{Binding Path=ImagePath}"
//包含ImagePath的ViewModel类
公共类WindowBackgroundViewModel:INotifyPropertyChanged
{
公共字符串ImagePath{get;set;}
}
//暗藏
public WindowBackgroundViewModel视图模型{get;set;}
//在构造函数中
公共myWindow()
{
this.ViewModel=新的WindowBackgroundViewModel();
this.ViewModel.ImagePath=@“C:\myBackground.png”;
this.DataContext=this.ViewModel;
}
//在XAML中