WPF绑定margin的问题

lucky-lucky 2013-08-12 01:21:26
请问在WPF当中如何绑定margin,下面的绑定语法是错误的,但是我只想绑定左边距,其它的边距全为0,如何来做?thanks

<Rectangle x:Name="TrackPath" Width="200"/>
<TextBlock Margin="{Binding ElementName=TrackPath,Value=Width} 0 0 0"/>
...全文
1082 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Bonjour-你好 2013-08-13
  • 打赏
  • 举报
回复
引用 4 楼 p569354158 的回复:
如何加转换
<Window x:Class="WpfTest.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTest"
        Title="Window1" Height="300" Width="300">
    
    <Window.Resources>
        <local:WidthToMarginConvert x:Key="WidthToMargin"/>
    </Window.Resources>
    
    <Grid>
        <Rectangle x:Name="TrackPath" Width="200" Fill="CadetBlue"/>
        <TextBlock Text="Test" FontSize="15" FontWeight="Bold" Margin="{Binding ElementName=TrackPath, Path=Width, Converter={StaticResource WidthToMargin}}" />
    </Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Data;

namespace WpfTest
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }

    public class WidthToMarginConvert : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Double width = (Double)value;
            return new Thickness(width, 0, 0, 0);
        }

        //没有用到
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}
  • 打赏
  • 举报
回复
引用 6 楼 p569354158 的回复:
[quote=引用 3 楼 rui_china 的回复:] textblock.Margin = new Thickness(20,0,0,0);
只能使用代码控制吗?可不可以使用XAML[/quote] “使用代码控制”有两种层次。一种是专业程序员做的工具,做好了之后给专业的善用xaml的交互界面设计师反复利用。 #1楼所说的转换器,以及许多类似的设计知识(例如behavior等等)属于这一类。这种代码才是专业开发人员应该做的。
lucky-lucky 2013-08-12
  • 打赏
  • 举报
回复
引用 3 楼 rui_china 的回复:
textblock.Margin = new Thickness(20,0,0,0);
只能使用代码控制吗?可不可以使用XAML
lucky-lucky 2013-08-12
  • 打赏
  • 举报
回复
引用 2 楼 qldsrx 的回复:
<TextBlock>
    <TextBlock.Margin>
        <Thickness Left="200"/>
    </TextBlock.Margin>
</TextBlock>
可以这么设置该属性的
提示说不能在Thickness.Left上Binding,因为Left不是PropertyObject
lucky-lucky 2013-08-12
  • 打赏
  • 举报
回复
引用 1 楼 KumaPower 的回复:
加个转换??
如何加转换
灬浪子灬 2013-08-12
  • 打赏
  • 举报
回复
textblock.Margin = new Thickness(20,0,0,0);
qldsrx 2013-08-12
  • 打赏
  • 举报
回复
<TextBlock>
    <TextBlock.Margin>
        <Thickness Left="200"/>
    </TextBlock.Margin>
</TextBlock>
可以这么设置该属性的
Bonjour-你好 2013-08-12
  • 打赏
  • 举报
回复
加个转换??

111,095

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧