Один из вариантов - использовать разные DataTemplate
для этого окна, переопределить его в Window.Resources
.
В качестве альтернативы, вы можете найти DataTemplate
элементов в VisualTree
после того, как окно будет отображено / присоединено к нему.
Для этого вы можете найти элементы Window по типу, имени.Например, если у вас есть DataTemplate с некоторыми элементами и кнопка с именем
<DataTemplate DataType="{x:Type local:MachineItem}">
<StackPanel>
<TextBlock Text="{Binding Id}"></TextBlock>
<TextBlock Text="{Binding Name}"></TextBlock>
<Button x:Name="DeleteButton"> delete</Button>
</StackPanel>
</DataTemplate>
Вы можете найти DeleteButtons в окне, используя VisualTreeHelper
как
VisualTreeHelperExtensions.FindChild<Button>(this, "DeleteButton");
Я изменил версию расширения VisualTreeHelperнайдено здесь , которое возвращает все элементы типа по имени
public static class VisualTreeHelperExtensions
{
public static IEnumerable<T> FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null)
{
yield break;
}
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foreach (var innerChild in FindChild<T>(child, childName))
{
yield return innerChild;
}
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
yield return (T)child;
}
}
else
{
// child element found.
yield return (T)child;
}
}
}
}
Итак, полный пример (с шаблоном, определенным выше):
private void OnInit(object sender, RoutedEventArgs e)
{
this.DataContext = new MachineItem("Type your description here",
MachineTypeEnum.Computer, "1.1.1.1", "1.1.1.1", 4, null, ((GUIApp)Application.Current).CurrentMachineGroup,
BordersStyle.Blue);
var buttons = VisualTreeHelperExtensions.FindChild<Button>(this, "DeleteButton");
foreach (var button in buttons)
{
button.Visibility = Visibility.Hidden;
}
}