[英]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.