在 Wpf 应用程序中,我有一个主窗口。
我在同一个项目中添加了一个用户控件。
在用户控件的 .xaml.cs 文件中,添加了一个依赖属性(属性的“值”名称)。
我想访问 usercontrol.xaml 中定义的依赖属性。
我知道我可以在 window.xaml 或其他一些用户控件中创建控件实例时做同样的事情。
但是是否可以在 .xaml 中访问 .xaml.cs 中定义的依赖属性?
问题基于 Vivs 答案更新
好的。我错误地提到了我的问题。尽管如此,即使我不知道访问。但我的实际预期问题是可以从 .xaml 设置依赖属性。像上面给出的例子中的一些东西,
<Grid CustomBackground ="{Binding Path= BackgroundColor}" />
或者
<Grid CustomBackground ="Blue" />
是否可以在同一个 .xaml 中设置这样的自定义依赖属性?
最佳答案
对的,这是可能的。
就像是:
.xaml
<UserControl x:Class="MvvmLight26.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MvvmLight26"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:UserControl1}}, Path=CustomBackground}" />
</UserControl>
和 .xaml.cs :
public partial class UserControl1 : UserControl {
public static readonly DependencyProperty CustomBackgroundProperty =
DependencyProperty.Register(
"CustomBackground",
typeof(Brush),
typeof(UserControl1),
new FrameworkPropertyMetadata(Brushes.Tomato));
public UserControl1() {
InitializeComponent();
}
public Brush CustomBackground {
get {
return (Brush)GetValue(CustomBackgroundProperty);
}
set {
SetValue(CustomBackgroundProperty, value);
}
}
}
替代:
如果你说有
DataContext
的UserControl
就像它本身一样:public UserControl1() {
InitializeComponent();
DataContext = this;
}
然后在您的 xaml 中,您可以使用:
<Grid Background="{Binding Path=DataContext.CustomBackground}" />
更新:
对于新问题,
不是很直接。
UserControl1
来自与原来相同的原始答案(只是 DP 部分。您需要删除它的 xaml 部分并使其成为代码隐藏中的非部分类),然后将其派生为新的 UserControl
. 就像是:
<local:UserControl1 x:Class="MvvmLight26.UserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MvvmLight26"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
CustomBackground="Blue"
mc:Ignorable="d">
<Grid />
</local:UserControl1>
您可以使用名称
UserControl1
如“BaseUserControl”之类的东西,以使其明显不用于直接使用。UserControl.Style
设置值也在同一个 xaml 中。 xml:
<UserControl x:Class="MvvmLight26.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MvvmLight26"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<UserControl.Style>
<Style>
<Setter Property="local:UserControl1.CustomBackground"
Value="Blue" />
</Style>
</UserControl.Style>
<Grid Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:UserControl1}}, Path=CustomBackground}" />
</UserControl>
关于wpf - 在同一个控件 xaml 中访问依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17468515/