我有一个问题,我无法解决:( 我有一个用户控件(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中的属性。
*的想法是,故事板是一个动画,将控件的大小调整到一定宽度取决于其父容器(宽度是动态的)
任何人?请 :) 谢谢!
答案 0 :(得分:2)
在CtrlContent构造函数中,指定DataContext = this;
然后在你的xaml:
<SplineDoubleKeyFrame Value="{Binding Path=MedWidth}"
这是让xaml在启动时至少从MedWidth属性读取一次所需的最低要求。如果您希望在MedWidth属性更改值时更新数据绑定,则需要在CtrlContent上实现INotifyPropertyChanged并发送更改通知。
请注意,将其分配给DataContext是一个草率的黑客攻击。它将你的整个课程暴露在房子的xaml一侧。 UI与逻辑的更好分离是创建一个仅用于数据绑定的独立小类,并将其分配给CtrlContent构造函数中的DataContext。这也将使INotifyPropertyChanged开销远离主类。
答案 1 :(得分:0)
您需要将MedWidth实现为DependencyProperty。