Combobox with images items-WPF - wpf

I'm newbie on WPF and I would like to add images items to combobox which will read from hard disk according filter on it's name.
filter on images name should be binds to text property of different element.
Any advice?
Thanks!

It is a good example to show MVVM approach. Code below will do the job:
XAML
<Window x:Class="simplest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:simplest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBox x:Name="outputFolder" Height="30" Margin="5" Grid.Column="0" Text="{Binding Filter}"/>
<ComboBox Height="30" Grid.Column="1" Margin="5" ItemsSource="{Binding Images}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image MaxWidth="64" MaxHeight="64" Source="{Binding}" />
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
C#
class MainWindowViewModel : INotifyPropertyChanged
{
private string _filter;
private ObservableCollection<string> _images = new ObservableCollection<string>();
private readonly string _filesSearchPath = "d:\\";
public MainWindowViewModel()
{
Filter = "*.jpg";
}
public string Filter
{
get
{
return _filter;
}
set
{
_filter = value;
OnPropertyChanged();
RefreshImagesCollection();
}
}
public ObservableCollection<string> Images
{
get
{
return _images;
}
}
private void RefreshImagesCollection()
{
_images.Clear();
foreach (var fileName in Directory.GetFiles(_filesSearchPath, _filter))
{
_images.Add(fileName);
}
}
private void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}

ItemTemplate and ItemSource are the properties you need to set.
ItemTemplate should point to Datatemplate and ItemSource to Collection of strings(path to images).
This link will help you.

Related

Wpf adding more views to tabcontrol dynamically with prism

I looking for a hint or just a direction how to design the structure I need because its a little tricky. I am using MVVM and Prism.
I have 2 regions, one with 2 buttons and one tabcontrol region. After clicking on button1 I want to inject 3 views as tabs into the tabcontrol. After clicking on button2 I want to remove the tabs from button1 (but keep the data behind) and inject again 3 views as tabs in the tabcontrol. And here comes the tricky part :-), this should happen dynamically and 2 of the 3 views from button1 and button2 are based on the same view/viewmodel.
I am thankfull for everything I can get :-D
You should be able to do this using the ViewModel first approach. Here is a quick and dirty way to do this, clean it up at your own convenience.
View/ViewModel structure:
View1 - ViewModel1 : IViewModel
View2 - ViewModel2 : IViewModel
View3 - ViewModel3 : IViewModel
IViewModel requires a "Content" string property
MainWindow.xaml
<Window x:Class="SFQ1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SFQ1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type local:ViewModel1}">
<local:View1/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel2}">
<local:View2/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel3}">
<local:View3/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<TabControl Grid.Row="0" ItemsSource="{Binding VmObservable}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Content}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentControl Content="{Binding}">
</ContentControl>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
<Button Grid.Row="1" Margin="10,0,0,0" Width="100" Content="1"
HorizontalAlignment="Left" Command="{Binding SetOneCommand}"/>
<Button Grid.Row="1" Margin="130,0,0,0" Width="100" Content="2"
HorizontalAlignment="Left" Command="{Binding SetTwoCommand}"/>
</Grid>
</Window>
MainViewModel.cs
public class MainViewModel : BindableBase
{
private readonly List<IViewModel> _viewModelCollection;
private ObservableCollection<IViewModel> _vmObservable;
public ObservableCollection<IViewModel> VmObservable
{
get { return _vmObservable; }
set
{
SetProperty(ref _vmObservable, value);
RaisePropertyChanged();
}
}
private IViewModel _activeVm;
public IViewModel ActiveVm
{
get { return _activeVm; }
set
{
SetProperty(ref _activeVm, value);
RaisePropertyChanged();
}
}
public DelegateCommand SetOneCommand { get; set; }
public DelegateCommand SetTwoCommand { get; set; }
public MainViewModel()
{
SetOneCommand = new DelegateCommand(SetOne);
SetTwoCommand = new DelegateCommand(SetTwo);
VmObservable = new ObservableCollection<IViewModel>();
_viewModelCollection = new List<IViewModel>()
{
new ViewModel1(),
new ViewModel2(),
new ViewModel3()
};
}
private void SetOne()
{
VmObservable.Clear();
VmObservable.Add(GetViewModel(typeof(ViewModel1)));
VmObservable.Add(GetViewModel(typeof(ViewModel2)));
VmObservable.Add(GetViewModel(typeof(ViewModel3)));
}
private void SetTwo()
{
VmObservable.Clear();
VmObservable.Add(GetViewModel(typeof(ViewModel2)));
VmObservable.Add(GetViewModel(typeof(ViewModel3)));
}
private IViewModel GetViewModel( Type viewModelType )
{
return _viewModelCollection.Find(x => x.GetType().Equals(viewModelType));
}
}

Why is ItemsControl in the following WPF XAML not showing anything?

When I run the app, I expect to see 5 buttons (see ItemsControl\DataTemplate\Button in my XAML below) each with a content like "55/42" denoting max ad min temperature. However, the window is blank. I know this has to do with ItemsControl because I can display the data without using the ItemsControl. Can someone catch my mistake?
<Window x:Class="Embed_WeatherSummaryAsItemsControl_ToMain.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
FocusManager.FocusedElement="{Binding ElementName=InputCity}"
Title="Weather App" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBox x:Name="InputCity" Grid.Row="0" Width="200" Text="{Binding CityAndOptionalCountry}"></TextBox>
<Button Grid.Row="0" Width="50" Content="Go" Margin="260,0,0,0" Command="{Binding GetWeatherReportCommand}"></Button>
<ItemsControl Grid.Row="1" ItemsSource="{Binding WeatherForecastSummaryCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Path=MaxMinTemperature}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
As shown below, "WeatherForecastSummaryCollection" is a collection property on ViewModel class and "MaxMinTemperature" is a property of item in collection.
public class MainWindowViewModel : ViewModelBase
{
....
private List<WeatherForecastSummary> mWeatherForecastSummaryCollection;
public List<WeatherForecastSummary> WeatherForecastSummaryCollection
{
get { return mWeatherForecastSummaryCollection; }
set
{
mWeatherForecastSummaryCollection = value;
OnPropertyChanged("WeatherForecastSummaryCollection");
}
}
.....
}
public class WeatherForecastSummary
{
public string MaxMinTemperature { get; set; }
}
Thanks for helping!
I think you are missing the DataContext here.
Even if you are using the codebehind of the View, you need to write
this.DataContext = this;
or if you are using someother class as viewmodel you might want to point the datacontext to that class. Just replace "this" in the above code with your viewmodels object.
In this case it would be ,
this.DataContext = new MainWindowViewModel();

Wpf contentControl

New programmer question:
I'm trying to create a simple navigation welcome page similiar to wht you whould see on an ipad.
My MainWindow has a titlebar (which wont change) and the rest will be a container of sorts that will show differnt things based on events.
So here is my question how do I bind the container (contentcontrol) to show other views ie show welcomeview originally and then if a user click on a button from the welcome view the content control shows the view they selected.
I currently has the Welcome Page as:
<UserControl x:Class="ContentControl.Views.WelcomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:ContentControl.ViewModels"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.DataContext>
<vm:WelcomeViewModel />
</UserControl.DataContext>
<Grid Background="red">
<Grid.RowDefinitions >
<RowDefinition Height="25*" />
<RowDefinition Height="50*"/>
<RowDefinition Height="25*"/>
</Grid.RowDefinitions>
<Rectangle Grid.Row="0" Fill="Green"/>
<DockPanel Grid.Row="1" HorizontalAlignment="Center" Background="White">
<Button Height="50" Width="50" Margin="5" Content="DASH" Command="{Binding ViewChangedCommand}" CommandParameter="Dashboard"/>
<Button Height="50" Width="50" Margin="5" Content="ROOM" Command="{Binding ViewChangedCommand}" CommandParameter="MeetingRoom"/>
<Button Height="50" Width="50" Margin="5" Content="SCREEN" Command="{Binding ViewChangedCommand}" CommandParameter="Screen" />
</DockPanel>
<Rectangle Grid.Row="2" Fill="Blue"/>
</Grid>
</UserControl>
The viewModel is as follows:
class WelcomeViewModel : BaseViewModel
{
private MainWindowViewModel _mainWindowVm;
private RelayCommand<string> _viewChangedCommand;
public ICommand ViewChangedCommand
{
get { return _viewChangedCommand ?? (_viewChangedCommand = new RelayCommand<string>(OnViewChanged)); }
}
public event EventHandler ViewChanged;
private void OnViewChanged(string view)
{
EventHandler handler = ViewChanged;
if (handler != null) handler(view, EventArgs.Empty);
}
public MainWindowViewModel MainWindowVm
{
get { return _mainWindowVm; }
set
{
_mainWindowVm = value;
OnPropertyChanged("MainViewModel");
}
}
public WelcomeViewModel()
{
MainWindowVm = new MainWindowViewModel();
ViewChanged += MainWindowVm.ViewChanged;
}
}
}
And I have my Mainwindow as follows:
<Window x:Class="ContentControl.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:ContentControl.ViewModels"
xmlns:views="clr-namespace:ContentControl.Views"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type vm:ScreenViewModel}">
<views:ScreenView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:WelcomeViewModel}">
<views:WelcomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:MeetingRoomViewModel}">
<views:MeetingRoomView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:DashboardViewModel}">
<views:DashboardView />
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<Label>This Is My Label</Label>
<ContentControl x:Name="MainPanel" Content="{Binding Content, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
MinHeight="200"
MinWidth="200"
HorizontalContentAlignment="Left"
VerticalContentAlignment="Center"
Focusable="False">
</ContentControl>
</StackPanel>
</Grid>
</Window>
Main Window View Model:
class MainWindowViewModel : BaseViewModel
{
private UserControl _content;
public UserControl Content
{
get { return _content; }
set
{
_content = value;
OnPropertyChanged("Content");
}
}
public void ViewChanged(object o, EventArgs e)
{
switch (o.ToString())
{
case "Welcome":
{
var welcome = new WelcomeView();
Content = welcome;
break;
}
case "MeetingRoom":
{
var meetingRoom = new MeetingRoomView();
Content= meetingRoom;
break;
}
case "Dashboard":
{
var dashboard = new DashboardView();
Content = dashboard;
break;
}
case "Screen":
{
var screen = new ScreenView();
Content = screen;
break;
}
}
MessageBox.Show(o.ToString());
}
public MainWindowViewModel()
{
}
}
}
How do I hook these Up to work with each other So I can show the WelcomeView as the content of the contentcontrol and then when I press a button have the ContentControl change to what was selected.
Again sorry I am new to MVVM and WPF and these binding are messing with my head.
The Buttons DASH, ROOM, SCREEN, should be on the MainWindow. The ViewChangedCommand should be on the MainWindowViewModel. And the content will be showed by dynamic templating.
If you want the buttons on the controls:
Ok so, then let's put the buttons on the controls, but the change content command should be in the MainWindowViewModel. To make a binding like this you should do something like this:
Command="{Binding Path=DataContext.ChangeContentCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
in your buttons

Trouble with DataBinding to a ListBox in WP7 which is not displaying the bound content

I have a DataBinding on a ListBox, bound to an ObservableCollection. Debugging at runtime shows the ObservableCollection does have items in it, and they're not null. My code all looks fine, however for some reason nothing is being displayed in my ListBox. It definitely was working previously, however it no longer is - and I can't figure out why. I've examined previous versions of the code and found no differences that would have any effect on this - minor things like Width="Auto" etc.
I based my code off of the example found here:
http://msdn.microsoft.com/en-us/library/hh202876.aspx
So, my code:
XAML:
<phone:PhoneApplicationPage
x:Class="MyNamespace.MyItemsListPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" x:Name="PageTitle" Text="MyPageTitle" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<!-- Bind the list box to the observable collection. -->
<ListBox x:Name="myItemsListBox" ItemsSource="{Binding MyItemsList}" Margin="12, 0, 12, 0" Width="440">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Width="440">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock
Text="{Binding MyItemNumber}"
FontSize="{StaticResource PhoneFontSizeLarge}"
Grid.Column="0"
VerticalAlignment="Center"
Margin="0,10"
Tap="TextBlock_Tap"/>
<TextBlock
Text="{Binding MyItemName}"
FontSize="{StaticResource PhoneFontSizeLarge}"
Grid.Column="1"
VerticalAlignment="Center"
Margin="0,10"
Tap="TextBlock_Tap" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
C#:
namespace MyNamespace
{
public partial class MyItemsListPage : PhoneApplicationPage, INotifyPropertyChanged
{
private static ObservableCollection<MyItem> _myItemsList;
private ObservableCollection<MyItem> MyItemsList
{
get
{
return _myItemsList;
}
set
{
if (_myItemsList!= value)
{
_myItemsList= value;
NotifyPropertyChanged("MyItemsList");
}
}
}
public MyItemsListPage ()
{
InitializeComponent();
this.DataContext = this;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
HelperClass helper = new HelperClass();
MyItemsList = helper.GetItems(this.NavigationContext.QueryString["query"]);
base.OnNavigatedTo(e); // Breakpoint here shows "MyItemsList" has MyItem objects in it.
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify Silverlight that a property has changed.
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
The Helper class is a connector to my read-only local database on the device. It returns an ObservableCollection<MyItem>:
public ObservableCollection<MyItem> GetItems(string itemName)
{
// Input validation etc.
// Selecting all items for testing
var itemsInDB =
from MyItem item in db.Items
select item;
return new ObservableCollection<MyItem>(itemsInDB);
}
And finally the MyItem class:
[Table]
public class MyItem: INotifyPropertyChanged, INotifyPropertyChanging
{
private int _myItemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int MyItemId
{
...
}
private string _myItemName;
[Column(CanBeNull = false)]
public string MyItemName
{
get
{
return _myItemName;
}
set
{
if (_myItemName!= value)
{
NotifyPropertyChanging("MyItemName");
_myItemName= value;
NotifyPropertyChanged("MyItemName");
}
}
}
private int _myItemNumber;
[Column]
public int MyItemNumber
{
get
{
return _myItemNumber;
}
set
{
if (_myItemNumber!= value)
{
NotifyPropertyChanging("MyItemNumber");
_myItemNumber= value;
NotifyPropertyChanged("MyItemNumber");
}
}
}
// Other properties, NotifyPropertyChanged method, etc...
}
This is rather frustrating as my DataBinding elsewhere in the application is working perfectly, so I've no idea why I can't get this to work.
The problem was that my ObservableCollection was private. Changing it to have a public access modifier allowed my ListBox to display the contents:
public ObservableCollection<MyItem> MyItemsList
Simply that you're binding to properties named incorrectly:
Text="{Binding ItemName}" should be Text="{Binding MyItemName}"
Notice you left out "My"

Accessing methods of a control that is in a Content Template

Relative WPF new-comer, this will probably have a simple solution (I hope!). I have a class with two properties:
public class MyClass
{
public String Name { get; set; }
public String Description { get; set; }
}
I have a user control which has a textblock and a button: the textblock displays text (obviously) and the button is used to either bold or unbold the text of the text block:
MyControl.xaml:
<UserControl
x:Class="WpfApplication1.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300"
xmlns:this="clr-namespace:WpfApplication1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="48" />
</Grid.ColumnDefinitions>
<TextBlock
x:Name="txtDescription"
Grid.Column="0"
Text="{Binding Path=Description, RelativeSource={RelativeSource AncestorType={x:Type this:MyControl}}}" />
<Button
x:Name="btnBold"
Grid.Column="1"
Content="Bold"
Click="btnBold_Click" />
</Grid>
</UserControl>
MyControl.xaml.cs:
public partial class MyControl : UserControl
{
public static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register("Description", typeof(String), typeof(MyControl));
public String Description
{
get { return GetValue(MyControl.DescriptionProperty) as String; }
set { SetValue(MyControl.DescriptionProperty, value); }
}
public MyControl()
{
InitializeComponent();
}
private void btnBold_Click(object sender, RoutedEventArgs e)
{
ToggleBold();
}
public void ToggleBold()
{
if (txtDescription.FontWeight == FontWeights.Bold)
{
btnBold.Content = "Bold";
txtDescription.FontWeight = FontWeights.Normal;
}
else
{
btnBold.Content = "Unbold";
txtDescription.FontWeight = FontWeights.Bold;
}
}
}
In my MainWindow I have a tab control which has an item template (to display MyClass.Name in the header of each tab) and a content template. The content template contains one of my above controls and MyClass.Description is bound to MyControl.Description:
MainWindow.xaml:
<Window
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525"
xmlns:this="clr-namespace:WpfApplication1">
<Grid>
<TabControl x:Name="tabItems">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<this:MyControl
Description="{Binding Description}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<MyClass> myClasses = new List<MyClass>();
myClasses.Add(new MyClass() { Name = "My Name", Description = "My Description" });
myClasses.Add(new MyClass() { Name = "Your Name", Description = "Your Description" });
tabItems.ItemsSource = myClasses;
}
}
When the program runs I add two objects of type MyClass to a List, set the list to the ItemsSource property of the tab control and it all works perfectly: I get two tabs with "My Name" and "Your Name" as the headers, the description is shown in the correct place and the button turns the bold on or off correctly.
My question is this, how do I add a button OUTSIDE of the tab control which could call the MyControl.ToggleBold method of the MyControl object which is in the content template of the selected item:
MainWindow.xaml:
<Window
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525"
xmlns:this="clr-namespace:WpfApplication1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TabControl x:Name="tabItems" Grid.Row="0">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<this:MyControl
x:Name="myControl"
Description="{Binding Description}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
<Button Grid.Row="1" Content="Toggle Selected Tab" Click="Button_Click" />
</Grid>
</Window>
MainWindow.xaml.cs:
...
private void Button_Click(object sender, RoutedEventArgs e)
{
MyClass myClass = tabItems.SelectedItem as MyClass;
MyControl myControl;
///get the instance of myControl that is contained
///in the content template of tabItems for the
///myClass item
myControl.ToggleBold();
}
...
I know I can access the data template by calling tabItems.SelectedContentTemplate but as far as I can tell I cannot access controls within the template (and I don't think I should be doing that either). There is the FindName method but I don't know pass as the templatedParent parameter.
Any help would be hugely appreciated.
You can navigate the VisualTree to find the control you're looking for.
For example, I use a set of custom VisualTreeHelpers which would allow me to call something like this:
var myControl = VisualTreeHelpers.FindChild<MyControl>(myTabControl);
if (myControl != null)
myControl.ToggleBold();

Resources