I have a lot of bindings in a grid which are collapsed or visible based on the selecteditem in a treeview tree. so based on the object, the correct view pops up and the other collapses.
But I get lots of binding errors of the gui elements in the collapsed views. that is so, because I have a "myselecteditem" in the view model that fits to the view which is opened, but not to the collapsed ones.
is my approach stupid? can i suppress bindings for gui elemnts in a collapsed grid?
Code (shorted for lazy readers):
XAML:
<Grid x:Name="G_G_Content" Grid.Column="1">
<Grid x:Name="G_G_Abrechnung_Control" Visibility="Collapsed">
[...]
</Grid>
<Grid x:Name="G_G_Mitglied_Aktion" Visibility="Collapsed">
[...]
</Grid>
<Grid x:Name="G_G_Mitglied_Aktion_Nachweis" Visibility="Visible">
[...]
</Grid>
</Grid>
<TreeView
x:Name="G_tv_explorer"
Grid.Row="1"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemsSource="{Binding TreeViewItemSource, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedItemChanged="G_tv_explorer_SelectedItemChanged"
TreeViewItem.Expanded="TreeViewItem_Expanded" />
C#:
private void G_tv_explorer_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
//set active treeviewitem
if (G_tv_explorer.SelectedItem != null)
{
//set treeview && ViMo
ViMo.TreeViewSelectedItem = e.NewValue;
RedrawGui();
ViMo.MySelectedItem = ((TreeViewItem)e.NewValue).Tag;
}
}
public void RedrawGui()
{
//redraw gui, dependant on selectedtreeviewitem
if (ViMo.TreeViewSelectedItem != null)
{
if(ViMo.TreeViewSelectedItem is string)
MessageBox.Show("Dummy");
else
{
//this is a placeholder
if (((TreeViewItem)ViMo.TreeViewSelectedItem).Header.ToString() == "Verwaltung")
{
G_G_Mitglied_Aktion_Nachweis.Visibility = System.Windows.Visibility.Collapsed;
G_G_Abrechnung_Control.Visibility = System.Windows.Visibility.Visible;
}
else if (((TreeViewItem)ViMo.TreeViewSelectedItem).Tag is MVVM.Model.Jahresabschluss)
{
G_G_Mitglied_Aktion_Nachweis.Visibility = System.Windows.Visibility.Collapsed;
G_G_Abrechnung.Visibility = System.Windows.Visibility.Visible;
}
}
}
}
Where RedrawGUI only sets the Grids Visible / collapsed based on the Object Type of the SelectedItem
Related
I need to build the UIElementCollection DetailsElement, after initializing the UserControl.
My problem lies in the FindName. I can't figure out how to use the TemplatedParent. Which element is that? an how can I refer to it in CB?
So DetailsElements would contain all the InputField elements in the DataGrid Details.
public partial class Segments
{
public Segments()
{
InitializeComponent();
// this does not work
var e = DgSections.FindName("MainPanel",...) as StackPanel;
DetailsElements = e.Children;
}
UIElementCollection DetailsElements;
...
<UserControl
x:Class="My.Views.MainUserControls.Segments"
.....
<DataGrid
x:Name="DgSections"
....
<DataGrid.Columns>
...
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Border Margin="0" Style="{StaticResource DataGridDetailsBorder}">
<StackPanel
x:Name="MainPanel"
...>
<muc:InputField
x:Name="Length"
.../>
<muc:InputField
x:Name="Diam"
... />
// and more InputFields
</StackPanel>
</Border>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
....
As mentioned in a comment, there is no Border element created by the time Segments is created. It's loaded and rendered on demand.
What you can do is to handle the Loaded event of the Border and programmatically set the properties of the InputFields:
private void SomeButton_Click(object sender, RoutedEventArgs e)
{
Border border = (Border)sender;
StackPanel stackPanel = (StackPanel)border.Child;
foreach (InputField inputField in stackPanel.Children.OfType<InputField>())
{
//...
}
}
XAML:
<Border Margin="0" Style="{StaticResource DataGridDetailsBorder}" Loaded="OnLoaded">
I have following working XAML and C# code behind:
<Grid x:Name="MainGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<GridView ItemsSource="{Binding}">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="100" Width="150">
<Grid.Background>
<SolidColorBrush Color="{Binding Color}"/>
</Grid.Background>
<StackPanel>
<StackPanel.Background>
<SolidColorBrush Color="{Binding Color}"/>
</StackPanel.Background>
<TextBlock FontSize="15" Margin="10" Text="{Binding Name}"/>
</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
CODE behind:
public MainPage()
{
this.InitializeComponent();
var _Colors = typeof(Colors)
.GetRuntimeProperties()
.Select(x => new
{
Color = (Color)x.GetValue(null),
Name = x.Name
});
this.DataContext = _Colors;
}
This works fine.
But I want to do all the XAML part in C# code behind. In XAML, only MainGrid will be there, all its child elements and bindings needs to be done in code behind.
I have tried something like this in MainPage_Loaded event:
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
try
{
GridView gridView = new GridView()
{
ItemTemplate = new DataTemplate
{
//Don't know what to add here
}
};
Grid grid = new Grid();
Binding bindingObject = new Binding();
bindingObject.Source = this;
grid.SetBinding(Grid.BackgroundProperty, bindingObject);
//...
// Don't know how to add grid inside gridView in Code.
//...
MainGrid.Children.Add(gridView);
}
catch (Exception ex)
{
}
}
First of all I'd like to advise you not to create elements in code unless you have a real good reason to do so.
Regardless, considering that item templates are factory-like objects for controls (you 'spawn' a new set of controls for each item). You use the FrameworkElementFactory to model the subtree and then assign that the item template's VisualTree property.
I have the following TabControl:
<TabControl ItemsSource="{Binding Tabs"}>
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type vm:TabVM}">
<TextBox></TextBox>
<TextBox Text="{Binding SomeProperty}"></TextBox>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
The unexpected behaviour is that first TextBox has Text property shared between all tabitems, while second TextBox effectively bind to ViewModel property.
My need is to make independent the first TextBox too, even without binding.
What can I do ?
** UPDATE **
After several tries I've decided to use the ikriv's TabContent.cs.
The only issue I've found with this is that calling the TabControl.Items.Refresh() (i.e. after removing a tabItem) cause the reset of the internal cache.
An unelegant but effective solution may be this:
public ContentManager(TabControl tabControl, Decorator border)
{
_tabControl = tabControl;
_border = border;
_tabControl.SelectionChanged += (sender, args) => { UpdateSelectedTab(); };
/* CUSTOM */
var view = CollectionViewSource.GetDefaultView(((TabControl)_tabControl).Items);
view.CollectionChanged += View_CollectionChanged;
}
/*
* This fix the internal cache content when calling items->Refresh() method
* */
private void View_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
/* Retrieve all tabitems cache and store to a temp list */
IList<ContentControl> cachedContents = new List<ContentControl>();
foreach (var item in _tabControl.Items)
{
var tabItem = _tabControl.ItemContainerGenerator.ContainerFromItem(item);
var cachedContent = TabContent.GetInternalCachedContent(tabItem);
cachedContents.Add(cachedContent);
}
/* rebuild the view */
_tabControl.Items.Refresh();
/* Retrieve all cached content and store to the tabitems */
int idx = 0;
foreach (var item in _tabControl.Items)
{
var tabItem = _tabControl.ItemContainerGenerator.ContainerFromItem(item);
TabContent.SetInternalCachedContent(tabItem, cachedContents[idx++]);
}
}
}
You should use data binding since the same ContentTemplate will be applied for all items in your ItemsSource. Only the binding will be refreshed when you switch tabs basically. The TextBox isn't re-created nor reset.
What can I do ?
You could work around this in the view by handling the SelectionChanged event of the TabControl and reset the TextBox control yourself:
private void tabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TabControl tc = sender as TabControl;
ContentPresenter cp = tc.Template.FindName("PART_SelectedContentHost", tc) as ContentPresenter;
if(cp != null && VisualTreeHelper.GetChildrenCount(cp) > 0)
{
ContentPresenter cpp = VisualTreeHelper.GetChild(cp, 0) as ContentPresenter;
if(cpp != null)
{
TextBox textBox = cpp.FindName("txt") as TextBox;
if (textBox != null)
textBox.Text = string.Empty;
}
}
}
<TabControl x:Name="tabs" ItemsSource="{Binding Tabs}" SelectionChanged="tabs_SelectionChanged">
<TabControl.ContentTemplate>
<DataTemplate>
<ContentPresenter>
<ContentPresenter.Content>
<StackPanel>
<TextBox x:Name="txt"></TextBox>
</StackPanel>
</ContentPresenter.Content>
</ContentPresenter>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
If you want to persist the text in the TextBox when you switch tabs you could use the attached behaviour from the following article and set its IsCached property to true: https://www.codeproject.com/articles/460989/wpf-tabcontrol-turning-off-tab-virtualization
<TabControl ItemsSource="{Binding Items}" behaviors:TabContent.IsCached="True">
<!-- Make sure that you don't set the TabControl's ContentTemplate property but the custom one here-->
<behaviors:TabContent.Template>
<DataTemplate>
<StackPanel>
<TextBox />
</StackPanel>
</DataTemplate>
</behaviors:TabContent.Template>
</TabControl>
Yet another approach would be to modify the ControlTemplate of the TabControl to include a ListBox as suggested by 'gekka' in the following thread on the MSDN forums: https://social.msdn.microsoft.com/Forums/en-US/4b71a43a-26f5-4fef-8dc5-55409262298e/using-uielements-on-datatemplate?forum=wpf
Here is my code. What it doing. I have one textbox(button) with text Book name, when I click on it I can change text in textbox using binding. But now I add another textbox for author name and I dont know how bind it. If I use same method like for Book name its not works or text from book name is too in book author. All text are changed via popup setting page.
My source here: https://dl.dropbox.com/u/40039421/App1.rar.
Image here: https://dl.dropbox.com/u/40039421/helpp.png
public partial class MainPage : INotifyPropertyChanged
{
private ObservableCollection<Book> _books = new ObservableCollection<Book>();
public ObservableCollection<Book> AllBooks
{
get { return _books; }
set { _books = value; }
}
...
private void InitializeData()
{
var bookName1 = new Book { Id = 1, BookName = "Small red apple",AuthorName = "Daniel"};
...
AllBooks.Add(bookName1);
...
OnPropertyChanged("AllBooks");
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
}
private void btnGreenBook_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
if (button != null)
{
Popup popup = new Popup();
popup.VerticalOffset = 30;
PopupSettingPage control = new PopupSettingPage();
popup.Child = control;
popup.IsOpen = true;
control.btnSave.Click += (s, args) =>
{
var id = Convert.ToInt32(button.Tag);
var book = AllBooks.FirstOrDefault(sub => sub.Id == id);
if (book != null)
{
book.BookName = control.BookName;
book.OnPropertyChanged("BookName");
}
popup.IsOpen = false;
};
...
Ohh dear, it was a simple mistake :)
You forgot to add the AuthorName in the Xaml of your PopupSettingsPage.xaml
<TextBox x:Name="tbInputAuthorName" Text="{Binding AuthorName, Mode=TwoWay}" VerticalAlignment="Center"/>
And then in MainPage do this
book.BookName = control.BookName;
book.OnPropertyChanged("BookName");
book.AuthorName = control.AuthorName;
book.OnPropertyChanged("AuthorName");
Additional answer based on your comments:
In order to achieve that, You have to remove the second stackpanel in the listbox. Instead, use the WrapPanel control. Search for how to use WrapPanel for WindowsPhone.
And then you have to find some way to set the backgrounds as red or green. Good luck
OK I use wrap panel but problem is still here. I have two panorama items (I post code from item 1 and item 2 have same code only is showing on second panorama page) and problem is still if I save some value to one of item in panorama item 1 this value is too in panorama item 2 and I dont know how make it. Logic is click on panorama 1 item change values in panoam 1 items, click on panorama 2 items change panorama 2 items values. Its look like panoram item 1 have same ID like panoram item 2. Here is full source : https://dl.dropbox.com/u/40039421/App1SecondEdit.rar
<Grid x:Name="LayoutRoot" Background="Transparent">
<!--Panorama control-->
<phone:Panorama>
<!--Panorama item 1-->
<phone:PanoramaItem Header="Test">
<Grid x:Name="PanelPanoramaItem1"
Grid.Row="1"
Margin="25,0,12,0">
<ListBox ItemsSource="{Binding AllBooks}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Width="140"
Height="140"
toolkit:TiltEffect.IsTiltEnabled="True" Margin="0,0,0,5" Click="Button_Click_1" Tag="{Binding Id}" >
<Button.Template>
<ControlTemplate>
<Grid Background="Chartreuse">
<TextBlock Foreground="Black" Text="{Binding BookName}" />
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</phone:PanoramaItem>
<!-- END Panorama item 1 -->
I have two table. Table 1 from a online service which forms the Listbox on my original Page. The second table is located in an internal DB and contains a uniqie field with the same values as a field in table1.
I want to use a listbox in table 1 to load details from table2 in a seperate page.
The code below is my code from my second page however it keeps throwing an exception "Items Collection must be empty before using ItemSource"
Can someone correct this code or sugest better way to do this?
public partial class PlayerProfilePanoramaPage : PhoneApplicationPage
{
object _SelectedPlayer;
string _playerName;
public CollectionViewSource viewsource { get; set; }
public PlayerProfilePanoramaPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(PhoneApplicationPage_Loaded);
LoadPlayerProfile();
LoadPlayerDetails();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = _SelectedPlayer;
}
private void LoadPlayerProfile()
{
FrameworkElement root2 = Application.Current.RootVisual as FrameworkElement;
var currentplayer = root2.DataContext as Mens_Leaders;
_SelectedPlayer = currentplayer;
_playerName = currentplayer.Name;
}
private void LoadPlayerDetails()
{
ObservableCollection<PlayerProfileTable> playerProfile = new ObservableCollection<PlayerProfileTable>();
viewsource = new CollectionViewSource();
viewsource.Filter += PlayerProfile_Filter;
viewsource.Source = playerProfile;
this.PlayerPanorama.ItemsSource = viewsource.View;
}
void PlayerProfile_Filter(object sender, FilterEventArgs e)
{
if (e.Item != null)
e.Accepted = ((PlayerProfile)e.Item).Name.Equals(_playerName);
}
}
edit: Xaml is currently only simple to text that binding was working. Datacontexts and source bindings not defined in Xaml as defined in code. Xaml code provided below.
<controls:Panorama Name="PlayerPanorama" Title="my application">
<!--Panorama item one-->
<controls:PanoramaItem Name="panoramaPage1" Header="item1">
<Grid Name="Grid1">
<StackPanel>
<TextBlock Height="30" Name="textBlock1" Text="{Binding PlayerName, FallbackValue=Name}" />
<TextBlock Height="30" Name="textBlock2" Text="{Binding Height, FallbackValue=Height}" />
<ScrollViewer Height="387" Name="scrollViewer1" Width="422">
<TextBlock Height="auto" Name="textBlock3" Text="{Binding ProfileBlurb, FallbackValue=Blurb}" />
</ScrollViewer>
</StackPanel>
</Grid>
</controls:PanoramaItem>