使用C#更改XAML对象的边距



需要帮助解决此问题。

我用初始化MainPage.xaml中的文本框

<TextBox 
    x:Name="box"
    HorizontalAlignment="Left"
    TextWrapping="NoWrap"
    Text="TextBox"
    VerticalAlignment="Center"
    RenderTransformOrigin="1.332,-26.438"
    Height="23" Width="1366"
    HorizontalContentAlignment="Left">
</TextBox>

然后我尝试用更改MainPage.xaml.cs中的边距

box.Margin = new Thickness(0,grid.Height - 23,0,0);

这是运行时错误

An exception of type 'System.Runtime.InteropServices.COMException'
occurred in Console.exe but was not handled in user code
Additional information: Error HRESULT E_FAIL has been returned from
a call to a COM component.

这是一张图片,显示了更改边距的代码和错误:http://screencast.com/t/U7pzizHzb

看起来你让这件事变得过于复杂了。您设置的边距将导致TextBox底部对齐,并强制为正好23像素高。那么,为什么不从一开始就这么做呢?

<TextBox ... Height="23" VerticalAlignment="Bottom" />

我不能100%确定是什么导致了你的COM错误,但我的第一个猜测是,你的"手动更改保证金"代码是在UI框架还没有准备好进行此类更改的时候运行的。(我发现WinRT在这种情况下非常脆弱。)因此,删除代码绑定并在XAML中指定布局,可能会修复COM错误,并使代码更简单、更易于维护。

最新更新