Binding chain with slider and text box in wpf - c#

I would like to binding as below:
A (in View) <---> B (in View) <----> C (MyData)
Binding A-B : Two way
Binding B-C : One way
Xaml
<Slider x:Name="slider" Minimum="0" Maximum="100" Value="{Binding Path=Text, ElementName=textBox, Mode=TwoWay}"/>
<TextBox x:Name="textBox" Text="{Binding Path=MyValue, Mode=OneWay}"/>
<Button x:Name="button" Content="Button" Click="button_Click"/>
Code Behind:
public int MyValue
{
get { return m_value; }
set
{
m_value = value;
NotifyPropertyChanged("MyValue");
}
}
...
private void button_Click(object sender, RoutedEventArgs e)
{
MyValue = 10;
}
I expect that when I click on button, the value of text box and slider bar will be updated.
However, nothing happen.
Please help me to solve this problem.
Thank in advance.

What you are trying to do is wrong in the architecture, that's why i would suggest you to take a look at some documentation about MVVM
such as:
https://www.codeproject.com/Articles/819294/WPF-MVVM-step-by-step-Basics-to-Advance-Level
or instead of considering just PRISM there are some more that are powerful but more approchable and easier such as MvvmLight:
http://www.dotnetcurry.com/wpf/1037/mvvm-light-wpf-model-view-viewmodel
Hope having been useful

Related

Binding TextBlock field to backend variable

First time really using WPF - thought I'd have a go at remaking something I did a while back in Java.
I'm trying to bind the Text value of a TextBlock on a popup to something that gets set in the backend, so I can use one handler method to display any message on said popup.
I've been trying multiple different routes, such as fully binding it in the cs instead of XAML like so:
<--XAML-->
<Popup Margin="89,75,0,0" Name="verif_popup" HorizontalAlignment="Left" VerticalAlignment="Top" IsOpen="False" PopupAnimation="Slide" Placement="Center" Width="100" Height="100" Grid.Column="1">
<Popup.Effect>
<BlurEffect/>
</Popup.Effect>
<Canvas Background="Azure">
<TextBlock Name="VerifTextBlock"/>
</Canvas>
</Popup>
<--CS-->
private void SmallPopupHandler(string text)
{
Binding binding = new("Text")
{
Source = text
};
VerifTextBlock.SetBinding(TextBlock.TextProperty, binding);
verif_popup.IsOpen = true;
}
But it doesn't like the fact that the string isn't a TextBlock property, I sort of knew this wouldn't work but it seems the most logical to me having come from swing. There also doesn't seem to be a way for me to cast it to it and im not in the mood for making my own dependency property rn...
The next thing I tried was to bind the value to a field in the class, but I just got a stackoverflow error (haha nice)
<--XAML-->
<Popup Margin="89,75,0,0" Name="verif_popup" HorizontalAlignment="Left" VerticalAlignment="Top" IsOpen="False" PopupAnimation="Slide" Placement="Center" Width="100" Height="100" Grid.Column="1">
<Popup.Effect>
<BlurEffect/>
</Popup.Effect>
<Canvas Background="Azure">
<Canvas.DataContext>
<local:MainWindow/>
</Canvas.DataContext>
<TextBlock Name="VerifTextBlock" Text="{Binding Popup_message}"/>
</Canvas>
</Popup>
<--CS-->
public partial class MainWindow : Window
{
public string? Popup_message { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
I also tried making an interfacing class of sorts to see if that would work around the stackoverflow error (haha) but as im sure you could have guessed by now, that didn't work either...
Kinda pulling my hair out so any help would be greatly appreciated!
Thanks in advance!
You could just set the Text property of the VerifTextBlock directly as suggested by #Clemens:
private void SmallPopupHandler(string text)
{
VerifTextBlock.Text = text;
verif_popup.IsOpen = true;
}
If you really do want to use a binding for whatever reason, then remove the binding path. This should work:
private void SmallPopupHandler(string text)
{
Binding binding = new()
{
Source = text
};
VerifTextBlock.SetBinding(TextBlock.TextProperty, binding);
verif_popup.IsOpen = true;
}

Unable to update binded control in Silverlight view

XAML code:
<TextBlock Text="Country" Foreground="white" TextAlignment="Right" Grid.Row="2" Grid.Column="0" />
<TextBox
x:Name="txtCountries"
Grid.Row="2"
Grid.Column="1"
Grid.ColumnSpan="2"
HorizontalAlignment="Stretch"
Margin="2, 2, 2, 2"
Text="{Binding PhysicalDeliveryParameters.Countries, Converter={StaticResource EnumerableToTextConverter}, ConverterParameter='...'}"
IsReadOnly="True">
</TextBox>
<Button
Grid.Row="2"
Grid.Column="3"
Content="..."
HorizontalAlignment="Left"
Tag="Countries"
Click="ButtonBase_OnClick" />
C# code :
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
PhysicalDeliveryParametersViewModel pvm = GetViewModel();
GenericObservableCollection<SelectableItem> items = pvm.Countries;
PhysicalDeliveryParametersDlg dlg = new PhysicalDeliveryParametersDlg(items);
dlg.Closed += (o, args) =>
{
BindingExpression binding = txtCountries.GetBindingExpression(TextBox.TextProperty);
if(null != binding)
binding.UpdateSource();
};
dlg.ShowDialog();
}
When I click on the button, the ButtonBase_OnClick() method executes : a dialog appears (PhysicalDeliveryParametersDlg class) and I choose some values. The binded data (PhysicalDeliveryParameters.Countries, which is an ObservableCollection) is updated, but not the Text property of my TextBox... Did I do something wrong ?
PS : I'm not sure I use the best method to create a modal window in Silverlight, could you give me some advice ?
It looks like the problem is that PropertyChanged never gets raised on the "Countries" property, so the view doesn't know it needs to update. (Actually, it probably wouldn't help to raise "PropertyChanged" in this case -- since the object reference has not changed, I believe the runtime would ignore it.)
I would just add another property "CountriesString" or similar:
Text="{Binding PhysicalDeliveryParameters.CountriesString}"
Update the property whenever is appropriate:
dlg.Closed += (o, args) =>
{
pvm.CountriesString = string.Join(", ", pvm.Countries);
};

Can I swap a buttons content databind to a different databind in code?

I cannot find any examples to make me understand how and if I can change the databind in c# at the click of a button on, in my case a toggleswitch, Basically I have 32 buttons in my app and those 32 buttons act the same but need different text with-in them depending on some toggle switches they are currently databinded so the text can be saved and retrieved from local storage but what values it gets depends on the state of these toggle switches.
So I currently have :
<Button x:Name="_ovButton1" Content="{Binding Source={StaticResource AppSettings}, Path=ovName1_1Value, Mode=TwoWay}" Margin="2,0,250,0" VerticalAlignment="Top" FontSize="14" Height="72" FontWeight="Bold" MouseLeftButtonUp="_ovButton1_MouseLeftButtonUp" MouseLeftButtonDown="_ovButton1_MouseLeftButtonDown" ClickMode="Hover" Hold="_ovButton1_Hold"/>
and I want when a user changes the state of a toggleswitch to change the
{StaticResource AppSettings}, Path=ovName1_1Value, Mode=TwoWay}
to for example:
{StaticResource AppSettings}, Path=ovName1_2Value, Mode=TwoWay}
but I cannot find any example that shows how to do that in c#
what code do I need to do that?
You can specify the target of databinding in code like this:
MyData myDataObject = new MyData(DateTime.Now);
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myText.SetBinding(TextBlock.TextProperty, myBinding);
See more at http://msdn.microsoft.com/en-us/library/ms742863.aspx
-- Edit Note I don't have access to a WP8 Emulator to test this ---
In the view model it looks like this:
public List<string> Members
{
get { return _Members; }
set { _Members = value; OnPropertyChanged(); }
}
public MainVM()
{
// Simulate Asychronous access, such as to a db.
Task.Run(() =>
{
Thread.Sleep(2000);
Members = new List<string>() {"Alpha", "Beta", "Gamma", "Omega"};
});
}
The code behind on the main page sets the datacontext (shared with all the child controls) as such:
public MainWindow()
{
InitializeComponent();
// Set the windows data context so all controls can have it.
DataContext = new MainVM();
}
The Mainpage Xaml to bind to members is like this
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[0] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[1] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[2] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[3] }" />
The result is this visually:
I based this on my blog article Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding for more info and a fuller example.
I think your best bet is going to be to use a collection of strings and bind to that collection. You can either change the collection when a toggle is switched, or keep 6 collections and bind to the collection that is for the toggle.
Xaml:
<ItemsControl x:Name="Buttons" ItemsSource="{Binding ButtonTextCollection}">
<ItemsControl.ItemsPanel>
<toolkit:WrapPanel/>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Width="100" Height="70" Content="{Binding}" Click="OnButtonClick"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Your code-behind would have the event handler for your button click
private void OnButtonClick(object sender, RoutedEventArgs e)
{
var text = ((Button) sender).Content.ToString();
// Send the text
}
Your ViewModel would hold the ButtonTextCollection property and would change based on the toggle.
public ICollection<string> ButtonTextCollection
{
get { return _buttonTextCollection; }
set
{
_buttonTextCollection = value;
OnPropertyChanged("ButtonTextCollection");
}
}
When you want to change the text, you would change the ButtonTextCollection
public void ChangeButtonText()
{
ButtonTextCollection = new Collection<string> {"A", "B",...};
}

trouble about setting value of slider in wpf?

I have a slider in wpf and want the user , set the min and max value of it.
in xaml code :
<Slider x:Name="slider1" Width="34" Minimum="{Binding Path=Minval}" Value="10" Height="105" Margin="5,5,5,5" Maximum="{Binding Path=Maxval}"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="5,5,5,5" Name="minvaltxt" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="5,5,5,5" Name="maxvaltxt" VerticalAlignment="Top" Width="120" />
<Button Content="Apply" Name="btn" Height="23" HorizontalAlignment="Left" Margin="5,5,5,5" VerticalAlignment="Top" Width="24" Click="btn_Click" />
in code behind :
private double maxval = 80;
public double Maxval
{
get { return maxval; }
set { value = maxval; }
}
private double minval = 5;
public double Minval
{
get { return minval; }
set { value = minval; }
}
private void btn_Click(object sender, RoutedEventArgs e)
{
minval= double.Parse(minvaltxt.Text);
maxval= double.Parse(maxvaltxt.Text);
slider1.Minimum = Minval
slider1.Maximum = Maxval;
}
but it does not update the min and max value of silder !
what is the problem ?
thanks for any help.
.
the question now edited.
thanks.
Have you set the DataContext for your view?
In Xaml you have used Maxcamdistance while the property name is Maxval in VM.
Implement INotifyPropertyChanged on your class and raise propertychanged for your property.
In button_click() set Properties not variables.
The problem is that you don't use dependency properties or INotifyPropertyChanged to inform the UI that the values of Minval and Maxval were changed. Have a look at my answer here: Bind boolean to visualstate
Thanks for all of lovely users who try to help .
Finaly I found the solution.
Infact , it did not need INotifyPropertyChanged or dependency properties !
The problem was about using 2 Windows Form Host in the same windows that causes one of
numericupdown return zero !
I do not khow why this accured but I used UserControl to overcome this problem.
User Control supports multiple Windows Form Host without any problem.
It seems that wpf windows has a limitation for hosting windows form.
Thanks alot.
Be Fresh.

MVVM binding double click to method using telerik radtreecontrol

I've been working on this problem for a stupid amount of time. It is time to ask for directions despite my inner man saying "don't do it."
I am coding in WPF C# using MVVM design pattern. We try to adhere strictly to the pattern and put nothing in the code behind unless there is no option or it is completely unreasonable to do so. Having said that, I am working with a Telerik RadTreeView. Here is a snippet of it in my XAML:
<telerik:RadTreeView IsExpandOnSingleClickEnabled="True" IsLineEnabled="True" Margin="5"
ItemsSource="{Binding ItemsView}"
SelectedItem="{Binding SelectedWidget, Mode=TwoWay}"
ItemTemplate="{StaticResource NodeTemplate}" />
Currently the tree is working properly so that if you highlight a tree item and click the OK button on the view, all is good. However, I need to also allow the user to double click on one of the tree items. This means I already have a command and method, protected override void OkAction(), in my view model with the needed logic. Telerik supplies a property called ItemDoubleClick that is supposed to supply functionality for the tree item double click. But I can't find anything to allow me to do this in the view model. In other words, how do I do the binding? We also have a behavior setup in our project for double clicking that I was told I could use, but I have no experience with behaviors. I'm still a little wet with WPF.
If it helps, here is a link to the documentation for Telerik: http://www.telerik.com/help/wpf/radtreeview-events-overview.html
I would appreciate any help or direction anyone can provide.
Try this out Stan:
<Grid.Resources>
<DataTemplate x:Key="WidgetTemplate">
<StackPanel Orientation="Horizontal">
<Image Source="/Resources/gear1.png" Margin="1" Stretch="None" />
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" Margin="6,0,0,0" />
</StackPanel>
</DataTemplate>
<HierarchicalDataTemplate x:Key="NodeTemplate" ItemsSource = "{Binding Children}" ItemTemplate="{StaticResource WidgetTemplate}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</Grid.Resources>
This is where you are going to want to possibly use the Attached Behavior that you already have for the DoubleClick.
Otherwise, here is the complete code that I use which creates the Attached Behavior and will create two Attached Properties which bind to a Command and optionally a Command Parameter.
AttachedBehaviors.cs
public static class MouseDoubleClick
{
public static DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command",
typeof(ICommand),
typeof(MouseDoubleClick),
new UIPropertyMetadata(CommandChanged));
public static DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached("CommandParameter",
typeof(object),
typeof(MouseDoubleClick),
new UIPropertyMetadata(null));
public static void SetCommand(DependencyObject target, ICommand value)
{
target.SetValue(CommandProperty, value);
}
public static void SetCommandParameter(DependencyObject target, object value)
{
target.SetValue(CommandParameterProperty, value);
}
public static object GetCommandParameter(DependencyObject target)
{
return target.GetValue(CommandParameterProperty);
}
private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
Control control = target as Control;
if (control != null)
{
if ((e.NewValue != null) && (e.OldValue == null))
{
control.MouseDoubleClick += OnMouseDoubleClick;
}
else if ((e.NewValue == null) && (e.OldValue != null))
{
control.MouseDoubleClick -= OnMouseDoubleClick;
}
}
}
private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
{
Control control = sender as Control;
ICommand command = (ICommand)control.GetValue(CommandProperty);
object commandParameter = control.GetValue(CommandParameterProperty);
if (command.CanExecute(commandParameter))
command.Execute(commandParameter);
}
}
.xaml - Remember to add the namespace of where the Attached Behavior lies.
<telerik:RadTreeView IsExpandOnSingleClickEnabled="True"
IsLineEnabled="True"
Margin="5"
ItemsSource="{Binding ItemsView}"
SelectedItem="{Binding SelectedWidget, Mode=TwoWay}"
ItemTemplate="{StaticResource NodeTemplate}"
acb:MouseDoubleClick.Command="{Binding ShowItemCommand}" />
SampleViewModel.cs
private RelayCommand _showItemCommand;
public RelayCommand ShowItemCommand
{
get
{
return _showItemCommand ?? (_showItemCommand =
new RelayCommand(ShowItemDetails, IsItemSelected));
}
}
obviously I don't have Telerik code so I can't really help as much as i would like to but you can try something like this. (Disclaimer: I am writing from top of my head)
Define your style in Grid.Resources
<Style TargetType="{x:Type RadTreeViewItem }" x:Key="TreeViewItemStyle">
<EventSetter Event="MouseDoubleClick" Handler="{Binding DoubleClick}" />
</Style>
Add the Style to Container Style.
<telerik:RadTreeView IsExpandOnSingleClickEnabled="True" IsLineEnabled="True" Margin="5"
ItemsSource="{Binding ItemsView}"
SelectedItem="{Binding SelectedWidget, Mode=TwoWay}"
ItemTemplate="{StaticResource NodeTemplate}"
ItemContainerStyle ="{StaticResource TreeViewItemStyle}"/>
Let me know if it works.
I tried several ways to get this accomplished.In the end I found that VS2012 was giving me fits. I noticed that changes weren't being applied on a build and run.
I opened VS2010 to find I wasn't experiencing the same issues. After speaking with my boss, we found this to be a good example of a situation that adhering to MVVM may not be the wisest choice since double clicking was strictly UI related.
I simply bounced through the code behind and into the view model using the instantiation of the view model as the data context. Didn't take but a second to do that.
As for the other solutions, I am sure it is completely possible, but I cannot confirm or deny the posts I've made here because of my VS2012 issues.

Categories

Resources