[英]WPF binding to current class property
我有一个我无法解决的问题:(我有一个用户控件(XAML文件和CS文件)
在xaml中,就像:
<UserControl
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="Demo.CtrlContent"
x:Name="UserControl"
d:DesignWidth="598.333" d:DesignHeight="179.133" xmlns:Demo="clr-namespace:Demo" >
<UserControl.Resources>
<Storyboard x:Key="SBSmall">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="border" Storyboard.TargetProperty="(FrameworkElement.Width)">
<SplineDoubleKeyFrame KeyTime="00:00:01" Value="I WANT TO BIND VALUE HERE"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
<Border BorderBrush="#FFC2C0C1" CornerRadius="3,3,3,3" BorderThickness="1,1,1,1" RenderTransformOrigin="0.5,0.5" x:Name="border" Margin="1,3,1,3" HorizontalAlignment="Left" VerticalAlignment="Top" Width="300">
和.cs文件:
public partial class CtrlContent {
private mindef W { get { return (mindef) Window.GetWindow(this); } }
public double MedWidth { // I WANT BIND THIS VALUE GO TO STORYBOARD VALUE IN XAML ABOVE
get {
double actualW;
if(W == null) actualW = SystemParameters.PrimaryScreenWidth;
else actualW = W.WrapMain.ActualWidth;
return actualW - border.Margin.Left - border.Margin.Right;
}
}
public double SmlWidth { get { return MedWidth / 2; } }
public CtrlContent () { this.InitializeComponent(); }
public CtrlContent (Content content) {
this.InitializeComponent();
Document = content;
}
}
在我的.cs文件中,有一个名为MedWidth的属性,在XAML文件中有一个故事板:SBSmall我想将我的故事板值绑定到类ctrlcontent中的属性。
*想法是,情节提要是一个动画,可根据其父容器将控件的大小调整为某个宽度(宽度是动态的)
任何人? 请:)谢谢!
在CtrlContent构造函数中,分配DataContext = this;
然后在您的xaml中:
<SplineDoubleKeyFrame Value="{Binding Path=MedWidth}"
这是使xaml在启动时至少从MedWidth属性读取一次的最低要求。 如果要在MedWidth属性更改值时更新数据绑定,则需要在CtrlContent上实现INotifyPropertyChanged并发送更改通知。
请注意,将其分配给DataContext有点草率。 它使您的整个班级都可以在房子的xaml一侧运行。 UI与逻辑的更好区分是创建一个单独的小类,该小类仅用于数据绑定,然后将其分配给CtrlContent构造函数中的DataContext。 这也将使INotifyPropertyChanged开销保持在您的主类之外。
您需要将MedWidth实现为DependencyProperty 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.