【发布时间】:2013-03-04 15:42:21
【问题描述】:
我有一个ListBox 绑定到一个为内部控件的文本属性提供数据的源。现在,我想将我的文本框的 Foreground 属性绑定到与主 ListBox 绑定的源不同的源!
我的列表框绑定到 ObservableCollection,我希望我的 textblock Foreground 属性绑定到位于 ViewModel 中的 textColor
public SolidColorBrush textColor
{
get { return new SolidColorBrush(Colors.Red); }
}
两者都属于ViewModel 类。
我尝试使用Foreground="{Binding textColor}",但似乎 XAML 根本看不到它,我应该在页面中执行任何操作以便它可以看到它,还是因为父级 (ListBox) 正在使用不同的来源?
编辑:
更多细节:
我有一个DataContext.cs 类,我在其中定义了我的表。
我有一个ViewModel.cs 类,里面有这些
public class CViewModel : INotifyPropertyChanged
{
private CDataContext myDB;
public CViewModel(string DBConnectionString)
{
myDB = new CDataContext(DBConnectionString);
}
private ObservableCollection<Groups> _allGroups;
public ObservableCollection<Groups> AllGroups
{
get { return _allGroups; }
set
{
_allGroups = value;
NotifyPropertyChanged("AllGroups");
}
}
public string textColor
{
get { return "Tomato"; }
}
}
然后我有我的 XAML 文件MainPage.xaml:
....
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Margin="0,8,0,0" toolkit:TiltEffect.IsTiltEnabled="True" x:Name="list" ItemsSource="{Binding AllGroups}" HorizontalAlignment="Center" BorderThickness="4">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="Orange" Width="125" Height="125" Margin="6" Tap="Counterlist_OnTap">
<TextBlock Name="gname" Foreground="White" Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap"/>
<TextBlock Name="ccl" Margin="0,0,0,-5" Foreground="{Binding textColor}" Text="{Binding Count}" FontSize="26" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
....
我还在后面的代码中将MainPage 的DataContext 设置为ViewModel:
this.DataContext = App.ViewModel;
【问题讨论】:
-
这应该可以正常工作。我采用了一个默认的 DataBound 应用程序,将您的属性添加到
ItemViewModel并在 MainPage.xaml 的第 36 行末尾添加了前景绑定,当在模拟器中运行时,它正确设置了文本块的颜色。请提供一个完整的示例来重现您的问题,我们将帮助确定您的问题所在。 -
感谢我编辑了帖子!
-
您现在已经定义了两次
textColor。是字符串还是 SolidColorBrush? -
是的,我将其更改为字符串,因为我认为在 XAML 中读取它时需要字符串!
-
如果您通过绑定设置它,则需要正确设置类型。 XAML 解析器将在执行初始解析时尝试转换字符串,但在绑定属性时您不会获得此自动转换。
标签: c# windows-phone-7 binding