Kry*_*oxx 5 c# wpf sizetocontent
每当我尝试制作一个窗口并将其设置SizeToContent为时WidthAndHeight,在打开窗口时正确调整其内容的大小,但它会在右侧和底部添加一个小边框.在调整大小时,它会消失,当使用设置的高度和宽度时,也不会出现此问题.
这是我的意思的样本:

你可以说这不是一个大问题,虽然我发现它使我的应用程序看起来不专业,特别是当我需要提出这个时.有谁知道为什么会这样,或者是否有解决方法?我正在用C#编写这个项目.
XAML代码:
<Window x:Class="FPricing.InputDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="InputDialog" Width="400" Height="300" SizeToContent="WidthAndHeight">
<StackPanel>
<Label x:Name="question">?</Label>
<TextBox x:Name="response"></TextBox>
<Button Content="OK" IsDefault="True" Click="Button_Click" />
</StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
在创建类时传递值.
但是,即使没有自定义底层代码,我也会在我创建的每个窗口上遇到此问题.
<Window UseLayoutRounding="True" /> 为我工作。
使用这个工具(它很好,顺便说一句)我发现(它的直接子级)Border的控件Window 没有填充整个窗口,留下了“边框”,它实际上是控件的背景Window。
我找到了解决方法。Width和Height的。Border NaN如果将它们设置为整数值,“边框”就会消失。
我们使用ActualWidth和的值ActualHeight,但四舍五入为整数。
定义转换器:
C#
[ValueConversion(typeof(double), typeof(double))]
public class RoundConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return Math.Ceiling((double)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
XAML(请记住包含您的命名空间,在本例中为“c”)
<c:RoundConverter x:Key="RoundConverter"/>
Run Code Online (Sandbox Code Playgroud)
然后使用转换器创建将尺寸绑定到实际尺寸的样式。使用 Key 很重要,因此它不适用于每个Border(大多数控件都使用它):
<Style TargetType="{x:Type Border}" x:Key="WindowBorder">
<Setter Property="Width" Value="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth, Converter={StaticResource RoundConverter}}"/>
<Setter Property="Height" Value="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight, Converter={StaticResource RoundConverter}}"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
最后,将此样式应用于窗口的第一个子窗口(控件Border):
private void Window_Loaded(object sender, RoutedEventArgs e) {
GetVisualChild(0).SetValue(StyleProperty, Application.Current.Resources["WindowBorder"]);
}
Run Code Online (Sandbox Code Playgroud)
如果有人可以以更简单的方式做到这一点,也请分享。
| 归档时间: |
|
| 查看次数: |
1317 次 |
| 最近记录: |