How to attach an object to an event in C#/.NET? - c#

I defined the following DataTemplate for a LibraryContainer:
<DataTemplate x:Key="ContainerItemTemplate">
<Grid>
<Border BorderThickness="1" BorderBrush="White" Margin="3">
<s:SurfaceTextBox IsReadOnly="True" Width="120" Text="{Binding Path=name}" Padding="3"/>
</Border>
<s:SurfaceButton Content="Expand" Click="SourceFilePressed"></s:SurfaceButton>
</Grid>
</DataTemplate>
The SourceFilePressed is the following:
private void SourceFilePressed(object sender, RoutedEventArgs e)
{
Logging.Logger.getInstance().log(sender.ToString());
e.Handled = true;
}
In the method SourceFilePressed who can I get the object that is binded to the SurfaceTextBox that is in the same grid as the pressed button? Can I somehow in the DataTemplate attach this object to the Click-Event?

If I parsed your question correctly, I think you could do this:
private void SourceFilePressed(object sender, RoutedEventArgs e)
{
var obj = (sender as FrameworkElement).DataContext;
}
To explain: the sender is the source of the event, so it's the SurfaceButton. It is a FrameworkElement and thus has a DataContext property. The DataContext is an inherited property, so unless you set it explicitly on the SurfaceButton, it will inherit it's DataContext from its parent (the Grid). The DataTemplate's DataContext is the data item it is templating, so you can see that the SurfaceButton will have that same object as its DataContext.

Related

c# How to find UIElements in RowDetailsTemplate

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">

UWP - get first child of Gridview

<GridView x:Name="MainGridStations" ItemsSource="{x:Bind Stations}" IsItemClickEnabled="True" ItemClick="GridView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate x:DataType="local:Station">
<Grid x:Name="WantToSelectByCode">
<Grid Background="White" HorizontalAlignment="Center" Width="300" Height="200" VerticalAlignment="Center">
<Grid Background="#e4f0fc" Height="65" VerticalAlignment="Bottom" Opacity="0.8">
<TextBlock x:Name="StationName" Text="{Binding Name}" FontWeight="Bold" Foreground="#2c9a8b" HorizontalAlignment="Center" />
</Grid>
</Grid>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
I'm trying to select a child by index of a dynamically filled gridview but what i've tried always returns null.
Like so for the first child for example:
var container = MainGridStations.ContainerFromIndex(0);
var presenter = VisualTreeHelper.GetChild(container, 0) as GridViewItem;
What am I doing wrong here?
You can get the corresponding GridViewItem from the method ItemsControl.ContainerFromIndex(Int32) directly and don't need to use the VisualTreeHelper to get it again.
var container = MainGridStations.ContainerFromIndex(0);
GridViewItem gridViewItem= container as GridViewItem;
gridViewItem.Background = new SolidColorBrush(Colors.Red);
The container have been the corresponding GridViewItem got from the index.
Note that: since your inner Grid have a Background="White" property configuration, you can delete the code to see the effect more obviously using my above code to change the gridViewItem.Background.
---Update---
You must get the GridViewItem after the items loaded. You can try the code in your GridView_ItemClick event handler or the page's loaded event hander. Also pay attention to my above note that to get more obvious effect, please delete the Background="White" in your above xaml code.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var container = MainGridStations.ContainerFromIndex(0);
GridViewItem gridViewItem = container as GridViewItem;
gridViewItem.Background = new SolidColorBrush(Colors.Green);
}
//get the item here
private void GridView_ItemClick(object sender, ItemClickEventArgs e)
{
var container = MainGridStations.ContainerFromIndex(0);
GridViewItem gridViewItem= container as GridViewItem;
gridViewItem.Background = new SolidColorBrush(Colors.Red);
//var presenter = VisualTreeHelper.GetChild(container, 0) as GridViewItem;
}

how to delete a selected template in a listbox

i have a listbox which has a data template binded to task from xml file,i want to delete selected template on button click,but its throws me an exception "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."
here is the code for xaml
<TabItem>
<Canvas Height="700" Width="850">
<Canvas.Resources>
<XmlDataProvider x:Key="Tasks" XPath="tasks"
Source="http://store.tymesheet.com/templates/Graphic-Designer.xml"/>
<DataTemplate x:Key="tasktemplate1">
<Canvas Height="50" Width="850" >
<Label Content="{Binding XPath=name}" Height="30"
Width="170" Canvas.Top="10" Canvas.Left="150"
Background="LightGray"/>
<TextBox Height="30" Width="120" Canvas.Top="10"
Canvas.Left="370" Background="AliceBlue"/>
<Label Canvas.Left="500" Canvas.Top="10">$</Label>
<Button Tag="{Binding}" Click="deletebuttonclick"
Canvas.Top="12" Height="10" Width="30"
Canvas.Left="600"/>
</Canvas>
</DataTemplate>
</Canvas.Resources>
<ListBox ItemTemplate="{StaticResource tasktemplate1}"
ItemsSource="{Binding Path=ChildNodes, Source={StaticResource Tasks}}"
x:Name="tasklistbox" Height="700" Width="850"/>
<Label Canvas.Top="-18" Canvas.Left="185">Select Task</Label>
<Label Canvas.Top="-18" Canvas.Left="377" RenderTransformOrigin="0.58,0.462">Enter Bill Rates</Label>
<Button Canvas.Left="39" Canvas.Top="575" Width="139">Click to add the task</Button>
</Canvas>
</TabItem>
here is the code behind for delete button
private void deletebuttonclick(object sender,RoutedEventArgs e)
{
tasklistbox.Items.Remove(tasklistbox.SelectedItem);
}
where am i wrong?,help.thanx.
The error that you displayed is fairly self explanatory:
Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
Clearly, as you should know, you used the ItemsSource property on the ListBox:
<ListBox ItemTemplate="{StaticResource tasktemplate1}"
ItemsSource="{Binding Path=ChildNodes, Source={StaticResource Tasks}}"
x:Name="tasklistbox" Height="700" Width="850" />
The error is telling you to Access and modify elements with ItemsControl.ItemsSource instead. So instead of not doing what it says:
private void deletebuttonclick(object sender,RoutedEventArgs e)
{
tasklistbox.Items.Remove(tasklistbox.SelectedItem);
}
Try actually doing what it says:
private void deletebuttonclick(object sender,RoutedEventArgs e)
{
tasklistbox.ItemsSource = null;
}
Or even better:
private void deletebuttonclick(object sender,RoutedEventArgs e)
{
ChildNodes = null;
}
UPDATE >>>
So it seems that we have another new user that asks one thing and when given that thing asks for another thing without so much as a 'thank you'... shame... a real shame.
First you need to data bind to the ListBox.SelectedItem property so that you know which item is selected:
<ListBox ItemTemplate="{StaticResource tasktemplate1}" SelectedItem="{Binding Item}"
ItemsSource="{Binding Path=ChildNodes, Source={StaticResource Tasks}}"
x:Name="tasklistbox" Height="700" Width="850" />
This Item property should be of the same type as the items in the ChildNodes collection... if it's not clear enough - you need to add that property next to your collection property. Then to remove that item in your handler, you just need to do this:
private void deletebuttonclick(object sender,RoutedEventArgs e)
{
ChildNodes.Remove(Item);
}
If you want to remove the item, then I would suggest to create ObservableCollection of XmlNode and bind ItemsSource with that. I suggested to use ObservableCollection because it implements INotifyCollectionChanged so whenever list is updated target which in your case is ListBox will automatically be updated.
In code behind
(Add System.Collections.ObjectModel namespace to use ObservableCollection<T>)
public MainWindow()
{
InitializeComponent();
XmlDocument doc = new XmlDocument();
doc.Load("http://store.tymesheet.com/templates/Software-Developer.xml");
var taskList = doc.ChildNodes.OfType<XmlNode>()
.Where(node => node.Name == "tasks")
.SelectMany(node => node.ChildNodes.OfType<XmlNode>());
Tasks = new ObservableCollection<XmlNode>(taskList);
this.DataContext = this;
}
public ObservableCollection<XmlNode> Tasks { get; set; }
private void deletebuttonclick(object sender, RoutedEventArgs e)
{
XmlNode selectedNode = ((Button)sender).DataContext as XmlNode;
Tasks.Remove(selectedNode);
}
Of course you need to update XAML as well:
<ListBox ItemsSource="{Binding Tasks}"
ItemTemplate="{StaticResource tasktemplate1}"
x:Name="listBox" Height="700" Width="850"/>

windows phone 8 imagebrush getting path

i have this code
<Grid Width="160" x:Name="grd">
<Grid.Background>
<ImageBrush x:Name="img" ImageSource="Assets/Icons/tab-inactive.png" />
</Grid.Background>
<TextBlock x:Name="txtacticve" Text="Rating" Tap="TextBlock_Tap_1" />
</Grid>
while tapping the textblock the tap event will be called.how can i get the complete path of the imagesource in this tap event in code behind? i am really at the lost here how to get to the imagesource in my codebehind event.
One solution could be the following one :
In your XAML code, you can bind your TextBlock.Tag property to the Grid.Background property you need. It could be useful to do it in XAML rather than code behind if your Grid is not the first parent (no need to find the required parent with recursive C# code) :
<Grid Width="160" x:Name="grd">
<Grid.Background>
<ImageBrush x:Name="img" ImageSource="Assets/Icons/tab-inactive.png" />
</Grid.Background>
<TextBlock x:Name="txtacticve" Text="Rating" Tap="TextBlock_Tap_1" Tag="{Binding ElementName=grd, Path=Background}" />
</Grid>
Then in your code behind, you just have to cast and use the TextBlock.Tag property that way :
private void TextBlock_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
var textBlock = sender as TextBlock;
if (textBlock != null)
{
var test = ((BitmapImage)((ImageBrush)textBlock.Tag).ImageSource).UriSource.OriginalString;
}
}
Try this.
private void TextBlock_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
var grid = (Grid)txtacticve.Parent;
var img = grid.Background;
var path = ((BitmapImage)(((ImageBrush)(img)).ImageSource)).UriSource.AbsolutePath;
}

How to extract value from selected TextBlock element in a ListBox?

I'm using a ListBox to display all values contained in Dictionary<> object:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Content is filled by the following code:
Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;
Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.
I tried doing something like that, but obviosly it doesn't work:
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
I would really appreciate your help!
you can even do the follwing:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid DataContext="{Binding ElementName=ContactsListBox, Path=SelectedItem}" Margin="0,470,0,0">
<TextBlock Text="{Binding Value}"/>
</Grid>
So you don't need code behind...
BR,
TJ
There are several problems:
In Xaml you probably don't want to display the class name, but a reasonable string, for example:
<TextBlock x:Name ="LastNameData" Text="{Binding Value.LastName}" Margin="20, 0" />
In the selection processing the selected item is KeyValuePair<...>. You could easily find it yourself, if you looked at the returned type in debugger. (Should be kind of a reflex for a programmer, hence a questions like above should never appear :))
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
KeyValuePair<long, Contact> kv = (KeyValuePair<long, Contact>)this.ContactsListBox.SelectedItem;
Contact c = (Contact)kv.Value;
Debug.WriteLine(c.LastName);
}
Your code is good, using ListBox.SelectedItem is the right approach.
I think the problem is that you should cast it as ListBoxItem, not ListBox. And also to get to its value using DataContext, so something like along these lines (not tested, I'm not sure about accessing DataContext value in the last line):
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = this.ContactsListBox.SelectedItem as ListBoxItem;
var dataContext = lbi.DataContext;
this.Test_SomeOtherTextBlock.Text = dataContext.Value.ToString();
}
Try this it works for me, will help you to...
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox ContactListBox = sender as ListBox;
ListBoxItem listBoxItem = ContactListBox .ItemContainerGenerator.ContainerFromItem(ContactListBox.SelectedItem) as ListBoxItem;
if (listBoxItem == null)
{
return;
}
TextBlock txtBlock = FindVisualChildByName(listBoxItem, "ListTextBlock");
MessageBox.Show(txtBlock.Text);
}
private static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
string controlName = child.GetValue(NameProperty) as string;
if (controlName == name)
{
return child as T;
}
T result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
return null;
}
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
will go something like this..
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
DataTemplate template=lb.ContentTemplate;
//Now here you have to extract the content of the data template
and then you need to extract the TextBlock from that content.
}
This is just an overview of the functionality.Sorry not able to post complete code.

Categories

Resources