我想绑定一些控件的边距,比如一个按钮,例如:
<Window.Resources>
<local:MarginConverter x:Key="marginConverter1"/>
</Window.Resources>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="{Binding MyThickness,
Converter={StaticResource marginConverter1}}">
<Button>Button1</Button>
</Grid>
根据参考。在这里:SO: Binding a part of the margin,我创建了一个MarginConverter
类和一个MyDataContext
类来实现INotifyPropertyChanged
界面(见下文),但Button1
仍然存在于顶层 - 左侧位置(好像其边距为0)。
Public Class MyDataContext
Implements INotifyPropertyChanged
Private _myThickness As Thickness = New Thickness(20, 10, 20, 0)
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Private Sub OnPropertyChanged(propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Public Property MyThickness As Thickness
Get
Return _myThickness
End Get
Set(value As Thickness)
_myThickness = value
OnPropertyChanged("MyThickness")
End Set
End Property
End Class
背后的代码:
Dim myDataContext1 As New MyDataContext()
Private Sub Window1_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
myDataContext1.MyThickness = New Thickness(20, 150, 20, 0)
End Sub
请帮助我澄清我的误解,即使您的基本知识或明确的解释也将不胜感激!
P / S:我绑定上边距的意图是当用户执行某项特定任务时,窗口顶部会出现25个高度的边框,因此所有现有控件都必须关闭。 / EM> 如果您有其他方法,请在这里分享。谢谢。
答案 0 :(得分:0)
如果您只想动态地在网格顶部提供25的高度, 您可以通过在网格的顶行添加边框并将其可见性更改为&#34; Collapsed&#34;到&#34;可见&#34;。
<Grid HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel>
<Border Height="25" Visibility="Collapsed">
</Border>
<Button >Button1</Button>
</StackPanel>
</Grid>
答案 1 :(得分:0)
好的,所以这里有适合你的例子,抱歉,但仅限于C# App.xaml中
<Application.Resources>
<ResourceDictionary>
<viewModel:TestVM x:Key="TestVm"/>
</ResourceDictionary>
</Application.Resources>
视图模型
public class TestVM : INotifyPropertyChanged
{
Thickness myThickness = new Thickness(20,10,20,0);
public Thickness MyThickness
{
get { return myThickness; }
set { myThickness = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Window1.xaml
<Window x:Class="WPF_Test_Canvas_Chart.Windows.Window1"
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"
xmlns:local="clr-namespace:WPF_Test_Canvas_Chart.Windows"
mc:Ignorable="d"
DataContext="{StaticResource TestVm}"
Title="Window1" Height="300" Width="300">
<Grid HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="{Binding MyThickness}">
<Button>Button1</Button>
</Grid>
</Window>
Window1.cs
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
var data = this.DataContext as TestVM;
data.MyThickness = new Thickness(100,10,20,0);
}
}