I have a string like follows.
string someInfo = string.Format("First Name = {0}, Last Name = {1}",firstName, lastName);
This string need to be displayed in application using TextBlock. The first and last names are coming from database so I would like to using data bindings for this. Is it possible to do?
Yes, its possible.
However, because you have multiple bindings, you need to bind to a MultiBinding
( MSDN ).
Your binding looks like:
<TextBlock.Text>
<MultiBinding Converter="{StaticResource NameConverter}">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
</MultiBinding>
</TextBlock.Text>
With a MultiValueConverter
:
public class NameConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return string.Format("First Name = {0}, Last Name = {1}", values[0], values[1]);
}
public objct ConvertBack(...)
{
return Binding.DoNothing;
}
}
I don't know whether you use the MVVM pattern. if you do just define a property in your ViewModel
public string Someinfo
{
get { return string.Format("First Name = {0}, Last Name = {1}",firstName, lastName);}
}
and then use a Binding in your Xaml
<TextBlock Text={Binding Path Someinfo} />
I would say this is 'cleaner' than doing that in your xaml.
yes it possible
public string SomeInfo { get; set; }
public MainWindow()
{
InitializeComponent();
SomeInfo = GetFirstNameAndLastNameFromDataBase();
DataContext = this;
}
private string GetFirstNameAndLastNameFromDataBase()
{
string firstName = "firstName";
string lastName = "lastName";
return string.Format("First Name = {0}, Last Name = {1}", firstName, lastName);
}
<Window x:Class="BindingToTextBlock.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">
<Grid>
<TextBlock Text="{Binding SomeInfo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
</Grid>
</Window>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.