C# 如何绑定窗口最大值&;孩子的起始尺寸
这是我的测试Xaml,它不能像预期的那样工作C# 如何绑定窗口最大值&;孩子的起始尺寸,c#,wpf,xaml,data-binding,window,C#,Wpf,Xaml,Data Binding,Window,这是我的测试Xaml,它不能像预期的那样工作 <Window x:Class="MyWindow.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" WindowStartupL
<Window x:Class="MyWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
WindowStartupLocation="CenterScreen"
SizeToContent="Manual"
Top="150"
MinHeight="90" MinWidth="90"
MaxHeight="{Binding ElementName=CPresenter, Path=MaxHeight,Mode=OneTime}"
MaxWidth="{Binding ElementName=CPresenter, Path=MaxHeight,Mode=OneTime}"
Height="{Binding ElementName=CPresenter, Path=Height,Mode=OneTime}"
Width="{Binding ElementName=CPresenter, Path=MaxWidth,Mode=OneTime}">
<Viewbox Name="viewer"
Stretch="Uniform">
<ContentPresenter Name="CPresenter">
<ContentPresenter.Content>
<UserControl MaxWidth="337" MaxHeight="156">
<Grid Width="50" Height="50" Background="Red"
MaxHeight="50" MaxWidth="100"/>
</UserControl>
</ContentPresenter.Content>
</ContentPresenter>
</Viewbox>
</Window>
上述代码应将窗口MaxWidth
和Width
设置为337
,还应将MaxHeight
和Height
设置为156
,但此绑定接缝中的任何一个都不起作用
没有错误,它只是不使用绑定。您正在将
绑定到名为CPresenter
的ContentPresenter
元素的MaxHeight
等属性,但您没有在该元素上设置这些属性。您可以在其内部的UserControl
上设置它们。此外,您根本不需要ContentPresenter
元素。试试这个:
<Viewbox Name="viewer" Stretch="Uniform">
<UserControl Name="CPresenter" Width="50" Height="50" MaxWidth="337"
MaxHeight="156">
<Grid Background="Red" />
</UserControl>
</Viewbox>
显然,您需要将UserControl
的名称更改为更好的名称,但是这应该是可行的。用户控件只有在运行时才知道,如果我使用snoop查看窗口,ContentPresenter的宽度和高度与我的用户控件中的宽度和高度相同,但即使绑定到这个值也会失败。我只是很愚蠢,我需要设置{binding Path=Content.Width,RelativeSource={RelativeSource Self}
并且它得到了正确的绑定