【发布时间】:2018-03-04 18:23:51
【问题描述】:
有人知道如何创建一个 XAML 字符串转换器,可以将字符串转换为 Grid.RowDefinitions 和 Grid.ColumnDefinitions 吗?
例子:
<Grid RowDefinition="auto,2*,2*" ColumnDefintions="auto,auto,*">
</Grid>
代替:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinitions Width="auto"/>
<ColumnDefinitions Width="auto"/>
<ColumnDefinitions Width="*"/>
</Grid.Columndefintions>
<!-- ahh...my fingers are so tired of typing XAML at this point!!!
-->
</Grid>
这里的一些代码几乎可以通过创建一个名为 MegaGrid 的新 Grid 来实现,该 Grid 具有可以按上述设置的“MegaRow”和“MegaCol”属性......只是目前不知道如何完成它。
public class MegaGrid : Grid
{
public static readonly DependencyProperty MegaRowProperty
= DependencyProperty.RegisterAttached(
"MegaRow", typeof(string),
typeof(MegaGrid),
new PropertyMetadata(-1, MegaRowChanged)
);
public static void MegaRowChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (!(obj is MegaGrid))
return;
MegaGrid grid = (MegaGrid)obj;
grid.RowDefinitions.Clear();
string value = (string) e.NewValue;
string[] items = value.Split(", \t");
foreach (string item in items)
{
//??? grid.RowDefinitions.Add(new RowDefinition { Height = });
}
}
public static readonly DependencyProperty MegaColProperty
= DependencyProperty.RegisterAttached(
"MegaCol", typeof(string),
typeof(MegaGrid),
new PropertyMetadata(-1, MegaColChanged)
);
public static void MegaColChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (!(obj is MegaGrid))
return;
MegaGrid grid = (MegaGrid)obj;
grid.ColumnDefinitions.Clear();
string value = (string)e.NewValue;
string[] items = value.Split(", \t");
foreach (string item in items)
{
//??? grid.ColumnDefinitions.Add(new ColumnDefinition { Width = });
}
}
}
这将使 XAML:
<local:MegaGrid MegaRow="auto,2*,2*" MegaCol="auto,auto,*">
...
</local:MegaGrid>
【问题讨论】:
-
这两个属性都不可绑定,因此绑定转换器将没有用处。但是,这可能会有所帮助:rachel53461.wordpress.com/tag/grid
-
作为一个一般性的提示(告诉一个在这里加入两年多,甚至自己写过答案的人,这是一个荒谬的提示),您或许应该考虑接受答案。见这里:What should I do when someone answers my question?
-
附带提示:不要使用 Grid 类的继承。相反,将此逻辑提取为行为类,以便您可以将其附加到任何 Grid(或相应的后代)。
-
我愿意接受你的评论,除非我不能这样做