Binding UserControl Width To A TextBox Input - wpf

It's my first time using the MVVM pattern and I have a bit of trouble understanding how everything ties together.
I have a UserControl with a Textbox element which should change the Width of said UserControl based on it's input.
I'm facing two problems:
For my idea to work, I need to change and bind to d:DesignWidth and my ColumnDefinition Width. How and where do I implement those changes? Based on my knowledge of MVVM the View (in this case my UserControl) is controlled by a ViewModel for said UserControl. Is it nessesary to implement one or is it possible to bind directly to both properties? I know I can name my ColumnDefinition with x:Name="MyColumnDefinition" but is the same possible for the actual UserControl Width?
mc:Ignorable="d"
d:DesignHeight="60" d:DesignWidth="170">
I have an ObservableCollection filled with two different UserControls and I want the Controls not to overlap when I display them. I use a ListBox element to display the ObservableCollection and implement the different UserControls over DataTemplates with a DataTemplateSelector. This works fine now but I'm worried if I dynamically change the Control Width that it will just overlap the next Control in the list. How do I ensure this won't happen?
Below is the code I have for now for the UserControl:
<Border Background="LightGray" CornerRadius="6">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Button VerticalAlignment="Top" HorizontalAlignment="Right" Grid.Column="2" Grid.Row="0"
BorderThickness="0" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DeleteCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DeleteCommandParameter}">
<Rectangle Width="8" Height="8" Fill="White">
<Rectangle.OpacityMask>
<VisualBrush Visual="{StaticResource appbar_close}" Stretch="Fill" />
</Rectangle.OpacityMask>
</Rectangle>
</Button>
<TextBlock Grid.Column="1" Grid.Row="0" FontSize="12" Margin="0,4,0,18" Foreground="White" HorizontalAlignment="Center" Grid.RowSpan="2">Delay</TextBlock>
<TextBox Grid.Column="1" Grid.Row="1" Width="46" Margin="0,4,0,16" HorizontalAlignment="Center" Grid.RowSpan="2"
Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=Delay.MiddlePosition, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<TextBlock Grid.Column="1" Grid.Row="2" FontSize="8" Margin="20,5,20,5" Foreground="Gray" HorizontalAlignment="Center">[s]</TextBlock>
</Grid>
</Border>
Edit:
ListBox-XAML to hold the other UserControls (I'm trying to build an Axis which can be filled with custom Positioning- and DelayControls:
<ListBox Name="Test" SelectionMode="Single" Grid.Column="1"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=BlockList}"
ItemTemplateSelector="{StaticResource BlockTemplateSelector}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Focusable" Value="False"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
End result should look kind of like this, but with differently sized Positioning and Delay blocks:

Check this code will help you to set width of one control to other control.
<Border>
<Grid x:Name="grv">
<TextBox Width="{Binding ElementName=grv,
Path=ActualWidth}">
</TextBox>
</Grid>
</Border>

I struggeled quite a while to figure out how to address your issue and even though I am not completely happy with the outcome, I managed to solve it.
First I create a ListBox with a DummyList, which contains Model-Objects called 'UserControlModel' with a singe Property 'modelWidth', from which I create my UserControls with their default size.
<ListBox ItemsSource="{Binding SimpleList, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Width="Auto" Height="200">
<ListBox.ItemTemplate>
<DataTemplate>
<osv:UserControl1 Width="{Binding modelWidth}" OnTextValidated="UserControlSizeChangeEvent"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
OnTextValidated is a RoutedEvent to hand up the KeyDown-Event from my Textbox to my Window(which i will show later)
The UserControl1.xaml then adds the textbox
<TextBox Width="60" Height="30" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" KeyDown="TextBox_KeyDown" Text="{Binding myText, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"></TextBox>
with a KeyDown event and a textbinding.
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)//press enter to change
{
if (double.TryParse(myText, out double d) == true)
{
if (d >= 50) //minimum width, so i won't set it to 0 by accident
{
myWidth = d; //set the new Width
OnTextValidated(this, new RoutedEventArgs()); //tell window to resize the UserControl
}
}
}
}
Once I validated the new size is neither wrong nor too small i call a RoutedEventHandler
private RoutedEventHandler m_OnTextValidated;
/// <summary>
///
/// </summary>
public RoutedEventHandler OnTextValidated
{
get { return m_OnTextValidated; }
set
{
m_OnTextValidated = value;
OnPropertyChanged("CustomClick");
}
}
now i can bind on this like shown above.
next i have to do is passing down my event from the xaml.cs to the MinWindowViewModel
//Variables
private MainWindowViewModel m_DataContext;
//Constructor
DataContext = new MainWindowViewModel ();
m_DataContext = (MainWindowViewModel)this.DataContext;
private void UserControlSizeChangeEvent(object sender, RoutedEventArgs e)
{
if (m_DataContext != null)
{
m_DataContext.UserControlSizeChangeEvent(sender, e);
}
}
and finally update the size of my object in my code behind
public void UserControlSizeChangeEvent(object sender, RoutedEventArgs e)
{
UserControl1 uc = sender as UserControl1;
uc.Width = uc.myWidth;
}
Note: Although this works quite fine i'd be much happier if i found a way to change the width of the model instead of the object, so they would still have the same width in case the list is redrawn.
I also didn't use a MVVM pattern for my UserContrl, so you'll have to pass the event from your xaml.cs to your viewmodel first like I did for the MainWindow

Related

ListBox inside ListBox, how do I know which button is clicked?

I have two ListBoxes, one inside another. And both ListBoxes will have items dynamically added into them upon user request.
Each time a button (not shown in the below code snippet) is clicked, a new item is added to the listbox. Each new item includes a new listbox and others.
And I have buttons inside the inner listbox, one for each list item of the inner listbox.
With DataContext, I can find the data binded to the inner list item, and make changes to it, so that changes are reflected on the proper list item.
However, I also need to make changes to the data binded to the outer list item, which corresponds to the button. How can I know which one it is?
I have came up with a solution, which I believe it not elegant enough. By making changes to the model, I can have each inner data holds a reference to the outer data, so that I can find the data binded to the outer list item. This doesn't seem like a proper solution though. Do you have any suggestions?
Below is code snippet of the xaml. I've simplified it, hope it's easy to understand. I feel you don't have to read the whole code.
<ListBox Name="QuestionsListBox" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox Text="{Binding Question, Mode=TwoWay}" Grid.Row="0" HorizontalAlignment="Stretch" TextWrapping="Wrap"/>
<ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Click="ChoiceAddButton_Click" Height="72" Width="72" HorizontalAlignment="Left" BorderBrush="Transparent">
<Button.Background>
<ImageBrush ImageSource="/Images/choices.add.png" Stretch="Fill" />
</Button.Background>
</Button>
<TextBox Text="{Binding Value, Mode=TwoWay}" HorizontalAlignment="Stretch" Grid.Column="1" Margin="-20,0" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Why not just use QuestionsListBox.DataContext inside ChoiceAddButton_Click directly? You have a direct way to reference the outer ListBox from your code behind since you've given it a name, and DataContext is an accessible property.
private void ChoiceAddButton_Click(object sender, RoutedEventArgs e)
{
...
var outerLBDataContext= QuestionsListBox.DataContext;
...
}
This works fine for me in a demo solution using your provided XAML.
Edit 2:
Sorry, wasn't thinking. The Button's DataContext will be a Choice, not the Choices collection.
Your inner ListBox's DataContext is not a Question, it's Choices. Your outer TextBox has Question.Question as its DataContext. Binding Text or ItemsSource makes the DataContext point to the binding target. Here is a bit of tricky XAML to sneak in a DataContext reference.
Add an ElementName to your outer TextBox:
<TextBox Text="{Binding Question, Mode=TwoWay}" Grid.Row="0" HorizontalAlignment="Stretch" TextWrapping="Wrap" ElementName="questionTextBox"/>
Now, add a hidden TextBlock inside your inner ListBox:
<ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Click="ChoiceAddButton_Click" Height="72" Width="72" HorizontalAlignment="Left" BorderBrush="Transparent">
<Button.Background>
<ImageBrush ImageSource="/Images/choices.add.png" Stretch="Fill" />
</Button.Background>
</Button>
<TextBox Text="{Binding Value, Mode=TwoWay}" HorizontalAlignment="Stretch" Grid.Column="1" Margin="-20,0" />
<TextBlock Name="hiddenTextBlock" Visibility="Collapsed" DataContext="{Binding ElementName=questionTextBox, Path=DataContext}"
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Finally, inside your event handler, you can navigate around the tree to get that reference:
private void ChoiceAddButton_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if(btn == null) return; //won't happen when this method handles the event
Grid g = btn.Parent as Grid;
if(g!=null) // also unlikely to fail
{
TextBlock tb = g.FindName("hiddenTextBlock") as TextBlock;
if(tb!=null) // also unlikely to fail, but never hurts to be cautious
{
var currentQuestion = tb.DataContext;
// now you've got the DC you want
}
}
}
I'd like to note that this isn't really an elegant solution. It is an all UI solution, however, which could be a useful thing. But better design would be to include Parent references in your Choice and ChoiceList (or whatever they're called) classes and use that. Then it would be as simple as calling btn.DataContext.Parent.Parent with appropriate type conversions. This way your code becomes easier to read and maintain.
You could add an event to your inner model that your containing datamodel subscribes to before adding it to the 'Choices' collection and pass the relevant information that way.
Is this necessary to use the Button control in your solution ??
If not fixed, then you can use the "Image control" as specified below <Image Source="/Images/choices.add.png" Height="72" Width="72" HorizontalAlignment="Left" Stretch="Fill"/>
If you use the Image control then in combination with this you can add the selection changed event to inner list box ( ChoicesListBox). Then in the Handler you can get the item selected as it comes as parameter with the selection changed event(SelectionChangedEventArgs).
Modify the List box and add the Selection changed event handler as below
<ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}" SelectionChanged="Items_SelectionChanged">
in page.xaml.cs you can add the handler and access the item as follows
private void Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems[0] != null)
{
//Please use the casting to the Choices items type to make use.
var temp = (ChoicesItemViewModel)e.AddedItems[0];
}
}

Zooming an item in Listbox/SurfaceListbox WPF

I am working on SurfaceListbox but I think the logic would apply to normal WPF listbox also.
I have the surfacelistbox with horizontal scroll enabled. It contains close to 20 items. The surfacelistbox is going to be placed in the center of the screen. Now when the user scrolls the listbox, the items move horizontally and based on the size of each item in the listbox, I have seen generally 3 items are visible at any given time on the screen.
Now what I want to do is, when the user stops scrolling and the 3 items are visible, I want to zoom in the center item i.e. basically enlarge it to highlight it.
Any pointers on how to implement such functionality in WPF would be great. Since the user doesnt make a selection when scrolling I could not use the selectionchanged event to know which one is the center item.
Place the SurfaceListBox in a Grid and bind ScaleTransform to a slider with a range from 1 to 5 centered in the Grid using RenderTransformOrigin="0.5,0.5".
The ItemsSource is set to an ObservableCollection; I include some definitions below for completeness to help others follow. I can provide more code if needed.
Here is the View:
<Window x:Class="SurfaceControls.MainWindow"
Icon="/Images/logo.gif"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Surface Toolkit Controls" Height="500" Width="600"
xmlns:my="http://schemas.microsoft.com/surface/2008" >
<Window.Resources>
<DataTemplate x:Key="EquipmentItemStyle">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=Id}"/>
<TextBlock Text="{Binding Path=EquipmentName}"/>
<TextBlock Text="{Binding Path=EquipmentType}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid RenderTransformOrigin="0.5,0.5" Grid.Row="0">
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform
ScaleY="{Binding Path=Value, ElementName=slider}"
ScaleX="{Binding Path=Value, ElementName=slider}"/>
</TransformGroup>
</Grid.RenderTransform>
<my:SurfaceListBox
ItemsSource="{Binding Path=Equipment, Mode=TwoWay}"
SelectedItem="{Binding Path=SelectedEquipment, Mode=TwoWay}"
ItemTemplate="{StaticResource ResourceKey=EquipmentItemStyle}" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"
VerticalAlignment="Stretch"
HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</my:SurfaceListBox>
</Grid>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<my:SurfaceSlider Ticks="5"
Width="100"
Minimum="1"
Interval="1"
Maximum="5"
x:Name="slider"
VerticalAlignment="Center"
Margin="4,4,4,4"/>
</StackPanel>
</Grid>
</Window>
Here this collection bound by the ListBox:
private ObservableCollection<Equipment> _equipment = new ObservableCollection<Equipment>();
public ObservableCollection<Equipment> Equipment
{
get
{
return _equipment;
}
set
{
_equipment = value;
}
}
And the defintion of the model:
public class Equipment
{
public int Id { get; set; }
public string EquipmentName { get; set; }
public string EquipmentType { get; set; }
}
Got useful information from these two links
http://social.msdn.microsoft.com/Forums/en-US/surfaceappdevelopment/thread/290f18c3-9579-4578-b215-45e6eb702470
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/5d486826-9a72-4769-bd09-ff6977e16c30

How do I access elements that have been dynamically assigned to a control in the form of an XAML resource?

I have the following resource in my window that declares how a certain kind of TabItem should look like.
<Window.Resources>
<StackPanel x:Key="TabSearchContents" x:Shared="False"
Orientation="Vertical">
<Border
BorderThickness="3"
BorderBrush="Purple">
<TextBlock
Text="SEARCH BOOKS"
FontFamily="Verdana"
FontSize="25"
Foreground="Blue"
HorizontalAlignment="Center" />
</Border>
<StackPanel
Height="30"
Orientation="Horizontal"
Margin="5">
<TextBox
x:Name="txtSearch"
Width="650"
FontFamily="Comic Sans MS"
Foreground="Chocolate" />
<Button
x:Name="btnSearch"
Width="100"
Content="Go!"
Click="BtnSearch_Click" />
</StackPanel>
<Grid x:Name="gridResults">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="450"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ScrollViewer Grid.Column="0" VerticalScrollBarVisibility="Auto">
<ItemsControl x:Name="itmsSearch" ItemsSource="{Binding}" Padding="4"
ItemTemplate="{StaticResource SearchResultItemDT}">
</ItemsControl>
</ScrollViewer>
<StackPanel x:Name="stkpnlDetails">
</StackPanel>
</Grid>
</StackPanel>
</Window.Resources>
Then, in my code-behind, I dynamically create a tab and assign to the TabControl that is already present in my window.
void BtnNewTab_Click(object sender, RoutedEventArgs e)
{
TabItem tb = new TabItem();
tb.Content = this.Resources["TabSearchContents"];
tb.DataContext = _bridge.SearchBooksByTitle("e");
tb.Header = "Wuttp yo!";
Button btnGo = ((Button)tb.FindName("btnSearch"));
ItemsControl i = (ItemsControl)tb.FindName("itmsSearch");
btnGo.Resources.Add("ResultList", i);
daTabs.Items.Add(tb);
tb.Focus();
}
I want to access the btnSearch Button that is declared in my XAML resource.
As it is, this code throws an exception since btnGo turns out to be null (as well as i) since it can't find the expected control via FindName().
I read about the RegisterName() method, but it requires a reference to an instance of the required control... which I don't have.
I dont think you should define your button like this, try defining it in a style, creating a button and assigning the button that style, i think you will be able to get what you are going for this way.
myTheme.xaml
<ResourceDictionary
<Style x:Key="btnSearch" TargetType="{x:Type Button}">
<Setter Property="Width" Value="100"/>
<Setter Property="Content" Value="Go!"/>
<Setter Property="Click" Value="btn_Click"/>
</Style>
ResourceDictionary/>
myCode.cs
Button btnGo = new Button;
btnGo.Style = "{DynamicResource btnSearch}";
Hope this helps,
Eamonn

Bind a generic list to a listbox and also use a datatemplate

I'm trying to implement something quite simple but I'm on my first steps in WPF and I'm having some problems. I have a class called Component which has a property called Vertices. Vertices is a generic List of type Point. What I want is to bind the vertices property to a listbox. This is easy by using this code in my XAML in the listbox declaration:
ItemsSource="{Binding Path=Component.Vertices, Mode=OneWay, Converter={StaticResource verticesconverter},UpdateSourceTrigger=PropertyChanged}"
The tricky part is when I try to create a datatemplate for the listbox. I want each row of the listbox to display a textbox with the values of the Vertex (Point.X, Point.Y) and a button to allow me to delete the item. Could you help me on the datatemplate definition. The code below doesn't work to bind the X,Y values into two separate textboxes. Could you point me on the mistake and why nothing is displayed in the textboxes?
<ListBox ItemsSource="{Binding Path=Component.Vertices, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<TextBox Text="{Binding X}" MinWidth="35" MaxWidth="35"/>
<TextBox Text="{Binding Y}" MinWidth="35" MaxWidth="35"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
/ListBox>
Something like this:
<ListBox ... Grid.IsSharedSizeScope="True">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A"/>
<ColumnDefinition SharedSizeGroup="B"/>
<ColumnDefinition SharedSizeGroup="C"/>
</Grid.ColumnDefinitions>
<Grid.Children>
<TextBlock Grid.Column="0" Text="{Binding X}" Margin="5"/>
<TextBlock Grid.Column="1" Text="{Binding Y}" Margin="5"/>
<Button Grid.Column="2" Tag="{Binding}" Margin="5" Click="Button_Click" Content="Remove"/>
</Grid.Children>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Event handler:
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
Button senderB = (Button)sender;
Point pt = (Point)senderB.Tag;
Collection.Remove(pt);
}
Note: Your list in the GUI will not get updated unless your bound collection implements INotifyCollectionChanged (Standard-implementation you can use: ObservableCollection<T>)
Edit: Common binding-fail causes:
1. Bound source is not a public property -> make it one
2. Binding path is not absolute and there is no DataContext to start from
-> Set DataContext of your window in the constructor to itself (this) or...
-> Set ElementName in the Binding to the name of your window if that is where your property is
Edit2: If your collection consists of Vertices and if your Vertex class contains a point with the property-name Point you need to change the bindings to {Binding Point.X} and {Binding Point.Y}, post more code next time please.

Silverlight: Applying datacontext to an element within a style

I have defined a style in app.xaml. This style contains several text TextBlocks which I would like to controle as I apply the style to an object, in this case a UserPin.
How can I access these TextBlocks runtime?
I get the style by:
Style = Application.Current.Resources["UserPin"] as Style;
The style looks like this:
<Style x:Name="UserPin" TargetType="RRML_UserControls:UserPin" >
<Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
<Setter Property="AnchorPoint" Value="0.5,0.5" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RRML_UserControls:UserPin">
<Grid Height="71.969" Width="Auto">
<Grid.RenderTransform>
<ScaleTransform x:Name="PART_PinScale" />
</Grid.RenderTransform>
<Grid.RowDefinitions>
<RowDefinition Height="29"/>
<RowDefinition Height="16"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.247*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="0.753*"/>
</Grid.ColumnDefinitions>
<Image Height="Auto" Source="Resources/Users.png" x:Name="PART_imgUser" VerticalAlignment="Top" Stretch="Uniform" Margin="0,0,0,0" Grid.Column="1">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
<TextBlock HorizontalAlignment="Center" Margin="0,0,0,0" Width="Auto" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Center" TextAlignment="Center" x:Name="txtBottom" Text="{Binding Mode=OneWay, Path=LocationName}">
<TextBlock.DataContext>
<RRML_RRMLServiceReference:Location LocationName="Initial Name"/>
</TextBlock.DataContext>
</TextBlock>
<TextBlock HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Center" Text="L" TextWrapping="Wrap"/>
<TextBlock Margin="0,0,0,0" Text="R" TextWrapping="Wrap" d:LayoutOverrides="Width, Height" Grid.Column="2" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The TextBlock value I'm trying to set is txtBottom.
As you can see I have tried to apply a datacontext and a databinding to the field. This works, but all objects get the value "Initial Name" of course.
My questions are:
how can I apply my datacontext so txtBottom.Text changes, or
how can I change the value of the TextBlock named txtBottom without databinding?
in short can I access these fields or properties at all?
Runtime :)
So far I have found that Triggers may be used only in WPF.
I think of something like this:
var styledobject = new NiceObject();
styledobject.Style = Application.Current.Resources["UserPin"] as Style;
styledobject.DataContext = locationData;
Where locationData is my object containing data.
If anyone wonders; I am placing icons on a map and want to name them.
You should not explicitly apply DataContext on the TextBlock. DataContext is inherited by child FrameworkElements. You should try to set data context explicitly as little and as high up the Visual Tree as possible (for your own sanity's sake :-))
If this is a custom control, you can override on the OnApplyTemplate method and use the GetTemplateChild(string name) to retrieve references to named elements within your control.
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
TextBlock txtBottom = GetTemplateChild("txtBottom") as TextBlock;
}
Externally, if you must, you can imperatively access that specific control at runtime using an extension method to traverse the Visual Tree to find it by name.
public static T FindChild<T>(this DependencyObject element, string name)
where T : FrameworkElement
{
//Code to find the control
}

Resources