我想将List中的String元素绑定到Textbox。当我单击一个元素时,文本会更新。但是当List中的元素更改时,文本框文本不会更改..
我的代码如下:
XAML:
<TextBlock Foreground="White" Name="xTitel" Text="{Binding Titel}" Width="200" FontSize="36" FontWeight="Bold"/>
OnClick功能:
foreach (Channel c in App.Connector.ChannelList)
{
if (c.StationName == StationName)
{
Binding b = new Binding();
b.Source = c.CurrentTitle;
xTitel.SetBinding(TextBlock.TextProperty, b);
}
}
频道定义:
public class GlobalVariables : INotifyPropertyChanged
{
public static MediaElement mediaElement;
private ObservableCollection<Channel> channelList;
public ObservableCollection<Channel> ChannelList
{
get { return channelList; }
set
{
channelList = value;
NotifyPropertyChanged("ChannelList");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
修改
我忘了说:
在我的XAML中,我有一个GridView,它与Channellist Binding一起使用。如果我是正确的,每当我的Gridview更新时,Textbox都应该更新。这是我的Gridview:
<local:VariableGridView
IsSwipeEnabled="True"
Background="Transparent"
x:Name="itemGridView"
Margin="0,0,0,-3"
Padding="116,0,40,46"
SelectionMode="None"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick"
Grid.RowSpan="2"
>
<local:VariableGridView.ItemsPanel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid Background="Transparent" Orientation="Vertical" ItemWidth="120" ItemHeight="120"/>
</ItemsPanelTemplate>
</local:VariableGridView.ItemsPanel>
<local:VariableGridView.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding Background}">
<StackPanel Orientation="Horizontal" Margin="10,0,0,0">
<Image x:Name="CurrentCover" Source="{Binding CurrentCover}" Width="90" Height="90"/>
<StackPanel Orientation="Vertical" HorizontalAlignment="Left" Margin="10,25,10,10">
<TextBlock Foreground="White" Text="{Binding Name}" Width="200" FontSize="24" FontWeight="Bold"/>
<TextBlock Foreground="White" Text="{Binding CurrentArtist}" Width="200" FontSize="12" FontWeight="Bold" />
<TextBlock Foreground="White" Text="{Binding CurrentTitle}" Width="200" FontSize="12" />
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</local:VariableGridView.ItemTemplate>
</local:VariableGridView>
Channel类:
public class Channel : INotifyPropertyChanged
{
public int Width { get; set; }
public int Height { get; set; }
public string Logo { get; set; }
public string StationName { get; set; }
public string Color { get; set; }
public SolidColorBrush Background { get; set; }
//public string Name { get; set; }
private string name;
public string Name
{
get { return name; }
set
{
name = value;
NotifyPropertyChanged("Name");
}
}
//..... More Code ...
}
(此Gridview中的文本框执行更新。但是其他文本框,我想在代码上设置绑定不会更新)
答案 0 :(得分:1)
应该这样吗?
Binding b = new Binding("CurrentTitle");
b.Source = c;
xTitel.SetBinding(TextBlock.TextProperty, b);
编辑以解释一下:如果直接绑定到字符串属性,您将看不到更改,因为字符串是不可变的。它将永远设置在原始字符串上。您必须绑定到包含字符串属性的对象,并为绑定提供一个属性名称(路径)以监视更改。