【发布时间】:2011-06-14 05:13:33
【问题描述】:
以下代码运行良好。代码的其他地方有错误。不过,给出的建议还是不错的。
我正在尝试将TextBox 的Width 绑定到父控件的Width 的百分比。我知道我可以通过简单地设置 Margin 来完成类似的事情,但我想知道为什么这不起作用。
首先,我在我的用户控件的资源集合中设置了对IValueConverter 的引用:
<UserControl.Resources>
<local:TextBoxWidthConverter x:Key="txtWidthConv" />
</UserControl.Resources>
在主要的 xaml 中,我有以下内容:
<StackPanel Name="parentPanel" Width="300">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Hidden" Name="scroller" Width="{Binding Width,
ElementName=parentPanel, Converter={StaticResource txtWidthConv}}">
<StackPanel Orientation="Horizontal">
<TextBox></TextBox>
</StackPanel>
</ScrollViewer>
</StackPanel>
ivalueconverter 如下所示:
public class TextBoxWidthConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double result = (double)value;
if (!Double.IsNaN(result))
{
result = result * .25;
}
else
{
result = 100D;
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotImplementedException("Not implemented.");
}
#endregion
}
在这里设置 width 属性没有任何作用,更不用说设置IValueConverter。我希望 ScrollViewer 是父级 StackPanel 宽度的 1/4。
【问题讨论】:
-
我用静态设置的
Width尝试了你的 XAML,效果很好。 -
这里也一样,在 VS2008 中尝试过,
ScrollViewer的大小是ParentPanel的 1/4 - 如果删除TextBox周围的StackPanel,TextBox将扩大到ScrollViewer的大小?
标签: wpf binding width ivalueconverter