顯示的控件的大小我做的一個工具欄類控制布點一些,並需要隱藏按鈕的文本時,沒有足夠的空間。我已經成功地在Windows Forms中完成了這個工作,現在我已經將這個邏輯移植到了WPF中。但是這裏存在一個巨大的問題:爲了讓我的算法正常工作,我需要知道容器控件的期望寬度(要知道如果一切都可見,將需要多大)以及控件的實際寬度(要知道如何寬度的確是這樣,並且是否有足夠的空間用於所需的寬度)。第一個是可用的,儘管有時候有點倒退。 (如果有更多的空間可用,DesiredSize會增加以填充所有內容,儘管更少可以。)後者完全不可用!找出真正的(!)在WPF
我試着ActualWidth的,但如果電網是比窗口寬,ActualWidth的超過實際上是可見的。所以這一定是錯誤的。然後我嘗試了RenderSize,但它是一樣的。在我的測量呼叫後使用排列會導致更多怪異。
我需要知道的控制真的有多寬,而不是有多寬就認爲自己是。我如何確定這個尺寸?
更新:好吧,這裏的一些代碼。這個問題已經很長了,而且還不完整。這是來自Window的代碼隱藏。
private void ToolGrid_LayoutUpdated(object sender, EventArgs e)
{
AutoCollapseItems();
}
private void AutoCollapseItems()
{
if (collapsingItems) return;
if (ToolGrid.ActualWidth < 10) return; // Something is wrong
try
{
collapsingItems = true;
// Collapse toolbar items in their specified priority to save space until all items
// fit in the toolbar. When collapsing, the item's display style is reduced from
// image and text to image-only. This is only applied to items with a specified
// collapse priority.
Dictionary<ICollapsableToolbarItem, int> collapsePriorities = new Dictionary<ICollapsableToolbarItem, int>();
// Restore the display style of all items that have a collpase priority.
var items = new List<ICollapsableToolbarItem>();
EnumCollapsableItems(ToolGrid, items);
foreach (var item in items)
{
if (item.CollapsePriority > 0)
{
item.ContentVisibility = Visibility.Visible;
collapsePriorities[item] = item.CollapsePriority;
}
}
// Group all items by their descending collapse priority and set their display style
// to image-only as long as all items don't fit in the toolbar.
var itemGroups = from kvp in collapsePriorities
where kvp.Value > 0
group kvp by kvp.Value into g
orderby g.Key descending
select g;
foreach (var grp in itemGroups)
{
//ToolGrid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
//ToolGrid.Arrange(new Rect(ToolGrid.DesiredSize));
//ToolGrid.UpdateLayout();
System.Diagnostics.Debug.WriteLine("Desired=" + ToolGrid.DesiredSize.Width + ", Actual=" + ToolGrid.ActualWidth);
if (ToolGrid.DesiredSize.Width <= ToolGrid.ActualWidth) break;
foreach (var kvp in grp)
{
kvp.Key.ContentVisibility = Visibility.Collapsed;
}
}
//ToolGrid.UpdateLayout();
}
finally
{
collapsingItems = false;
}
}
更多的代碼:這裏的窗口XAML的一部分:
<Window>
<DockPanel>
<Grid Name="ToolGrid" DockPanel.Dock="Top" LayoutUpdated="ToolGrid_LayoutUpdated">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
...
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
這是使用在安排/措施期間?或者你是否通過綁定來做這件事? – user7116 2013-02-25 19:47:15
它在代碼隱藏中在LayoutUpdated事件(但不是遞歸)上調用。我也發現所需寬度總是小於實際寬度。如果沒有足夠的空間,則Desired是可見尺寸和實際需要的。如果有足夠的空間,則Desired是所需的大小和Actual可見。所以這兩個屬性的含義就轉過來了,我不知道哪個屬性是哪個。無用。 – ygoe 2013-02-25 19:57:12
有些代碼會有幫助,你是繼承'UserControl'還是'Control'? – user7116 2013-02-25 19:58:14